Sei sulla pagina 1di 257

1

Java
BASIC Concepts
OOPS:
Data Encapsulation : bind code together code with wrapper to the object Achieved through Private
constructors in Java.
Data Abstraction : designed with Implementation gaps for Sub classes to fill in.Achieve through
Abstract Classes & Abstract Methods. Avoid Complexity.
Abstract Class: Designed with implementation gaps for subclasses to fill in.
Abstract Method : Defines all aspects of itself except what code it executes.
Polymorphism: Object Taking more than 1 Form. Achieved in java through Method through Overloading
and Method Overriding.
Types of Polymorphism
Compile time Polymorphism - Method Overloading In a class two or more methods share the same
name differed by its arguments Handled as below.
class abc {
public abc1(int a) { }
public abc1(int a,int b){ }
//AdditonalCode.
}
Runtime Polymorphism - Method Overriding Instead of inheriting a method from its super class, a
subclass method writes it own definition for it. Handled as below.
class abc1 {
Public abc001(int a,int b) throws Exception { }
// Some code
}
class abc2 extends abc1 {
public abc001( int a ,int b) throws ClassNotFoundException { }
// please note any exception thrown in class abc2for the above method // should be
subclass of exception of method abc001 given in class abc1
// some code
}
Inheritance A subclass uses method definitions, constructors and variables from a superclass
just as they belong to subclass itself.
Types Of Inheriatance.
Single Inheritance
Multi Level Inheritance
Multiple Inheritance(Achieved through Interfaces).
// For Inheritance method , The sub class method should have the same access specifier as its super
class method.
Alternative way to Inheritance , Use Dynamic Binding / Late Binding [ if the class to be imported is in
same package its ok else import that package.
Order to Follow while writing a Java class
Package a;
Import Java.io.*;
Import java.lang.*; // not need 2 import Java.lang as its imported by default.No harm in importing again.
Class class_Declaration {
// Global Variable Declarations.
// Inner Class [if required ]
// Method Declarations.
// Other Descriptions whatever required.
}

2
VARIOUS TYPES TO CREATE INSTANCE OF A CLASS
1. Using new Operator : class_def c1 = new c1ass_def() // create instance for class class_def.
class_def c1 = new class_defenition() // create instance for class class_defenition which is a
different class, always note that wherever we go for declaration ,we should know that new is the
operator that creates instance [ refers to memory allocation of class.
2. Using Class that returns a runtime value of a class
3. Create instance of a class invoke a constructor.
Class A{
// implementation methods
}
Class B extends A {
// Implementation code
A a = new B();
}
What will happen here.
Ans : Though we give A a = new B() it will work , it will refer to class A not B. We can access
Class A methods not class B.
What will happen for B b = new A() Results in Class cast Exception.
INTERFACES
Interface strip down of a class. Specifies set of methods that a instance must handle but omits
inheritance relationships and method implementations.
Public interface def {
//variables declared are final & static by default [if declare int I,its value must be defined 10]
//methods given without body
//abstract methods by default.
}
Advantage : globally Accessible in any part of the project
A interface extends another.
A interface is used as replacement for of Multiple inheritance.A class implement an interface using
implements keyword.
Class a extends abc implements def
// note abc is class, def a interface{ }
interface ghi extends def, xyz{ } // def and xyz are interfaces.
Marker interface A interface defined with out any methods.
Different types of compilers available in java
1.Javac Compiler
2.JIT compiler.
Work of a compiler Loading ,Linking , Initialization.

3
Abstract class
Defines full set of methods
Follows inheritance relationships.
Class and methods are explicitly declared with
K/W abstract to refer as abstract methods, refers
can have non abstract methods too.
Cannot have final or static variables.
Abstract class can have constructors as nonabstract method but not Recommended,since no
need to create instance.Instance will be created
when its subclass object is invoked.
Abstract class Scope is restricted to that particular
package alone.

Interface
Defines subset of methods that a instance must
handle.
Omits inheritance relationships but replaces multiple
inheritance in java.
No need to use keyword abstract as all methods are
abstract by default
Variables declared are final and static by default.
Constructors not allowed.

Scope of a interface is global to the whole


application.

ABSTRACT CLASS WITH CONSTRUCTOR :


All the classes including the abstract classes can have constructors.Abstract class constructors will be
called when its concrete subclass will be instantiated
The purpose of abstract class is to provide common information for the subclasses.The abstract classes
cannot be instantiated.You will get a compile error.
An abstract class can have methods with full body apart and abstract method.
This is especially useful when extending classes.Say,you have an super class Animal and sub-classes
Dog,Cat,Cow etc.All the different type of animals have one thing comon.ie,sound.So the Animal class has
methods to define these sub-classes and also a method called sound().Though this method does
nothing.It is only used in subclasses and implemented.It is just declared in Animal class but not defined.
JRE JRE is Java Runtime Environment. It is a place where java classes are run. Like in the case of an
applet, a JRE needs to be installed on the web server where you are going to run the applet.

JVM It is a program designed for different environment Java Virtual Machines operate on Java
bytecode, which is normally (but not necessarily) generated from Java source code; a JVM can also be
used to implement programming languages other than Java
what is diff bet framework and design pattern?
Design pattern is how to implement for a particular problem. Framework is designed on the design
pattern.
eg. Struts designed with different design patterns
Java is strictly pass-by-value, no pass by reference.
Class A blue print for objects.
Object - A software unit that combines structured set of data with set of operations for inspecting and
manipulating that data.
- Instance created to a
class.
Object Reference : a Object Pointer with strong restrictions for integrity and safety.
Signature of Method : combination of Method Name and Method input types.
Static :dontholdanyspecificstate
No need to create instance
Accessed directly by instance ref
Value defined with static can be modified.

4
Staticmethodscannotbeoverriddensinceitdoesntbelongtoanystate
Static methods belong to the class, not specific objects of that class.
Static variables are accessed by static methods.
Native : other than java
public native int meth()
javah jni nativeDemo
Dis adv. --> Potential security risk.
--> Loss of portability
Volatile Permanent storage of memory.
Use master-copy of the variable for accessing.
Transient value is not constant.
instanceOf( ) It is a 2 argument operator that checks at run time whether the 1st
argument is
compatiable with the 2nd.
A a = new int A()
a.instanceOf(A);
Default Values
String = null; int = 0; float = 0.0; double =0.0; long = 0; Boolean = false; short = 0; byte=0;
Char=null;
Data Types. Range
Byte 28 to 28-1
byte b= (int) b+1 needstypecastingelsewontwork.
Short -216 to 216 -1
int -232 to 232-1
long -264 to 264 -1
float 1.2e -302 to (1.2e302)-1
Array
int a[] =new int[10] ; - allocates 10 spaces 0-9
int a1[][] = new int[10][10] - allocates 100 spaces 0-99
Arithemetic Operators +, - , * , / , %
Ternary Operator
Exp1 ? exp2 : exp3, Exp1 : true exp2, Exp1 : false exp3
Instance Variable
Class Variable
A separate data item for each instance of a
A Single data item shared by a class & its
class.
instances.
Eg. Class Eg. { int i1; }
Class eg { static int i1; }
Instance Method
Can use this instance ref .
Static Block
static block can access multiple threads

Class Method
No this instance reference available.
Static Synchronized Block
proceeds with single thread access at a time

Constructor: It is a method having same name as of the class,


Need not be instantiated.Since instantiation is done automatically when create object for the class
Cantreturnavalue,
adding void to constructor returns a error.
can be overloaded, cannot be overridden,
refer to particular class only ,
variables assigned is taken implicitly.
A class can have more than one constructors through overloading concept
Constructors without args will be called first ahead of other constructors.

5
Method
Will have different name of the class.
Need to be instantiated by a object of the
class.
Values defined inside a class is accessed
through objects.
Value may be returned.
Can be overloaded and overridden

Constructor
Same name of the class.
Need not be instantiated.
Values are taken implicitly.
Cannot return value.
Cannot be overridden can be overloaded.

Super explicit access to constructors, Methods, variables of its super class.


Must be the 1st valid statement in any method.
This refers to current object.
Must be the 1st valid statement in any method.
Key Words in Java 47 + 2 Reserved words( const ,goto) .true, false are also reserved words. As on java
version 1.4.
operator overloading is not possible in java but we can overload + operator implicitly how?
for eg. String s = "Abc";
s=s+"d" will give s="Abcd"
Possibilities :
Object o= String s; Possible, since you assign a string that is subclass to Object [Super class]
Object to Integer ? no not possible, Since Integer is a Wrapper class & it holds the functionality to
convert primitive Data types to Objects.
To get all public methods in a class getMethods()
Different Types of Classes
1. Abstract Class Designed with implementation gaps for subclasses to fill in.
2. Adapter Class empty method implementation of a class.used to handle events avoid complexity.
3. Final Class [properties] cannot be sub-classed.
Final Method cannot be overridden , can be overloaded.
Final Variable cantchangeitsvalueassigned.
If Final Class is sub-classed, results in Compiler Error.
4. Anonymous class:Aclassdefinedinsideamethoddoesnthaveaname.Itdoesnthave
constructors also. It is generally used to get the properties of the class.
5. Inner class A class defined inside another class. It is different from inheritance
relationships. It can have all the properties of a class includes constructors, method
definitions etc. it is used to reduce complexity.
6. Concrete Class It is a class defined by the programmers with full set of method implementations
and variables. It can access an abstract class /interface or anything.
7. Singleton class : a class that create only one instance.
Will have all methods declared static
Constructors given are private constructors.
For Singleton class to avoid cloning of class do the following
1. Make the singleton class implements java.lang.cloneable
2. Give method public void clone()

6
3. throw new cloneNotSupportedException
4. doing the above will not allow object to get duplicated.
8. Wrapper class convert primitive(pre defined) data type into objects.
Integer I = new Integer();
Primitive data types cannot be accessed directly. For that we use Wrapper class
Different Wrapper classes
1. Integer,
2. Float,
3. Character
4. Boolean
5. Long
6. Short
7. Byte
8. Double
JAVA.lang.* - Default import
SYSTEM.OUT.PRINTLN()
System a class in java.lang
Out Static object reference of printwriter class
Println() - a method in printwriter class.
Advantages of JDK 1.5
1. has better handling of generic introduction
2. better in handling collection objects.
ArrayList <String> = new ArrayList <string>
3. StringBuilder class used in placed of Asynchronous StringBuffer.
Adding Annotations
Annotations in Java is all about adding meta-data facility to the Java Elements. Like Classes, Interfaces or
Enums, Annotations define a type in Java and they can be applied to several Java Elements. It can be
seen in class declaration, method declaration, field declaration etc. The added Annotation to Java
Elements have proven themselves to be considerably useful in many instances.
public @interface TestAnnotation
{
// Property Definition here.
}
Types of Annotation
1. Target Annotation
Annotation can only be applied to methods, then there is a Meta-Annotation
(meta-data about meta-data) which tells for which element type this annotation is applicable.
@Target(ElementType.METHOD)
public @interface TestAnnotation
{
// Property Definitions here.
}
2. Retention Annotation
Retain the Annotation in the Source Code only
Retain the Annotation in the Class file also.
Retain the Annotation Definition during the Run-time so that JVM can make use of it.
The Annotation that is used to achieve this is @Retention and it takes a possible values
of SOURCE, CLASS and RUNTIME defined in RetentionPolicy Enumeration

7
Example :
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.CLASS)
public @interface TestAnnotation
{
// Property Definitions here.
}
Synchronized block and Synchronized Statements.
A synchronized method uses the method receiver as a lock (i.e. this for non static methods, and the
enclosing class for static methods). Synchronized blocks use the expression as a lock.
synchronized void mymethod() { ... } void mymethod() { synchronized (this) { ... } }
synchronized blocks, you can use any non-null object as a lock:
synchronized (mymap) { mymap.put(..., ...); }
For synchronized methods, the lock will be held throughout the method scope, while in the synchronized
method, the lock is held only during the synchronized block (otherwise known as critical section). In
practice, the JVM is permitted to optimize by removing some operations out of the synchronized block
execution if it can prove that it can be done safely.
Autoboxing & Autounboxing
Java 5 also supports automatic unboxing, where wrapper types are automatically converted into their
primitive equivalents if needed for assignments or method or constructor invocations.Java 5 (and hence
AspectJ 1.5) supports automatic conversion of primitive types (int, float, double etc.) to their object
equivalents (Integer, Float, Double,...) in assignments and method and constructor invocations. This
conversion is know as autoboxing.
Its not possible to put an int (or other primitive value) into a collection. Collections can only hold
objectreferences,soitstheneedtoboxprimitivevaluesintotheappropriatewrapperclass(whichis
Integer in the case of int). its possible to take the object out of the collection, as Integer and put in; if
you need an int, you must unbox the Integer using the int Value method.
For Example
// Prints a employee table of the words on the command line
import java.util.*;
public class employeeTable {
public static void main(String[] args) {
Map<String, Integer> m = new TreeMap<String, Integer>();
for (String word : args) {
Integer emp = m.get(word);
m.put(word,emp ( == null ? 1 : map + 1));
} System.out.println(m);
}
}
java employee if it is to be it is up to me to do the watusi
{be=1, do=1, if=1, is=2, it=2, me=1, the=1, to=3, up=1, watusi=1}
The program first declares a map from String to Integer, associating the number of
times a word occurs on the command line with the word. Then it iterates over each word on the
command line. For each word, it looks up the word in the map. Then it puts a revised entry for the word
into the map. The line that does this (highlighted in green) contains both autoboxing and unboxing. To
compute the new value to associate with the word, first it looks at the current value (freq). If it is null,

8
this is the first occurrence of the word, so it puts 1 into the map. Otherwise, it adds 1 to the number of
prior occurrences and puts that value into the map. But of course you cannot put an int into a map, nor
can you add one to an Integer. What is really happening is this: In order to add 1 to freq, it is
automatically unboxed, resulting in an expression of type int. Since both of the alternative expressions in
the conditional expression are of type int, so too is the conditional expression itself. In order to put this
int value into the map, it is automatically boxed into an Integer.
The result of all this magic is that you can largely ignore the distinction between int and
Integer, with a few caveats. An Integer expression can have a null value. If your program tries to
autounbox null, it will throw a NullPointerException. The == operator performs reference identity
comparisons on Integer expressions and value equality comparisons on int expressions. Finally, there are
performance costs associated with boxing and unboxing, even if it is done automatically.
Generic Classes
Generics allow you to abstract over types
List<Integer> myIntList = new LinkedList<Integer>();
List<String> ls = new ArrayList<String>(); //1
Using Interfaces
small excerpt from the definitions of the interfaces List and Iterator in package
java.util:
public interface List<E> {
void add(E x);
Iterator<E> iterator();
} public interface Iterator<E> {
E next();
boolean hasNext();
}

Reg Annonymous and Inner classes


Additional properties to inner class
1. An inner class is a class defined inside another class
2. An inner class object is scoped not to the outer class, but to the instantiating object.
3. Even if the inner class object is removed from the outer class object that instantiated it, it retains
the scoping to its creator.
4. If an object has a reference to another object's ("parent object"'s) inner class object, the inner
class object is dealt with by that object as a separate, autonomous object, but in fact, it still has
access to the private variables and methods of its parent object.
5. An inner class instantiation always remembers who it's parent object is and if anything changes
in the parent object (e.g. one of its property's value changes), that change is reflected in all its
inner class instantiations.
6. Inner classes are very useful in factory pattern situations.
7. Inner classes cannot have static members. only static final variables
8. Inner classes may inherit static members that are not compile-time constants even though they
may not declare them.
9. If your class requires the use of a number of other classes that are related to each other (ie form
a class hierarchy) and those classes are particular to the parent class (ie are ideal candidates for

9
implementation as inner classes) then it is probable that the super class of the inner class
hierarchy will be abstract.
normal class declaration]
{
[scoping] class [inner class's name] [extends ....] [ implements ...]
{
// properties and methods of the inner class
}
// rest of properties and methods of parent class
}
Additional Properties of Inner Class
Anonymous inner classes are very similar to named inner classes:
Anonymous inner classes can override methods of the superclass. Anonymous inner
classes are scoped inside the private scoping of the outer class. They can access the internal
(private) properties and methods of the outer class. References to an inner class can be passed to
other objects. Note that it still retains its scoping. Anonymous inner classes must use the no
parameter constructor of the superclass.
Usages:
Very useful for controlled access to the innards of
another class.
Very useful when you only want one instance of a special class.
Anonymous Class
Since an object made from the inner class has
a "life" independent of its outer class object, there
is a problem with accessing local variables,
especially method input paramenters.

Inner Class
Initialize a property that the inner class then
uses -- properties have the cross-method-call
persistence that local variables lack. Two ways
to pass initializing parameters to an inner class:
Make the local variable "final" -- compiler will
automatically transfer the value to a more
persistent portion of the computer memory.
Disadvantage: the value cannot be changed.
Java.Lang.* [a package that is imported by java by default ,if imported again no harm ]
java.lang.Object Super class of All classes & objects.
constructor : public Object() Methods:
1. public final Class getClass( ) --> Returns the Class of this Object
2. public int hashCode( )
return hashCode.
Each Object in the Java system has a hashcode.
The hashcode is a number that is usually different for different Objects.
Stored in HashTable
Hashcode will be available @ toString() method before overriding on overriding the value is
modified.
Each class will have its own hashcode().Every object created to the class will have same
hashcode to the class.If used was to get hashcode .
Hashcode is a 32 bit integer ASCII that is used to find the argument of the class.
3. public boolean equals(Object obj) --> Compares two Objects for equality.
Returns a boolean that indicates whether this Object is equivalent to the specified Object. This method is
used when an Object is stored in a hashtable.
4. protected void copy(Object src) throws ClassCastException --> Copies the contents of
the specified Object into this Object. The contents of an Object are defined as the values of its
instance variables. The parameter src must be of the same Class as this Object. If obj is not of
the same type as this Object.

10

5. protected Object clone( ) throws OutOfMemoryError --> Creates a clone of this Object. A
new instance is allocated and the copy() method is called to copy the contents of this Object into
the clone. If there is not enough memory throw exception
6. public String toString( ) --> Returns a String that represents the value of this Object. It is
recommended that all subclasses override this method.
7. public final void notify( ) throws InternalError --> Notifies a single waiting thread on a
change in condition of another thread. The thread effecting the change notifies the waiting
thread using notify(). Threads that want to wait for a condition to change before proceeding can
call wait().can only be called from synchronized method.
8. public final void notifyAll( ) throws InternalError --> Notifies all of the threads waiting for
a condition to change. Throws error If the current thread is not the owner of the Object's
monitor.
9. public final void wait( long timeout) throws InterruptedException --> Causes a thread
to wait until it is notified or the specified timeout expires.
10. public final void wait( ) throws InterruptedException --> Causes a thread to wait forever
until it is notified.
Interfaces in Java.Lang.*.
1. runnable --> The Runnable interface should be implemented by any class whose instances are
intended to be executed by a thread. The class must define a method of no arguments called
public void run() { }
Cloneable --> empty method[marker] implemented interface. implemented to a class and override
objects clone method. It is used to get the duplicate copy of an object.
CloneNotSupportedException being thrown if class not implements cloneable interface.
Comparable --> This interface imposes a total ordering on the objects of each class that implements it.
This ordering is referred to as the class's natural ordering, and the class's compareTo() is referred to as
its natural comparison method.
Hashcode
Hashcode is a unique 32 bit ascii value for a particular class. A class can have n number of objects with
same Hashcode. Hashcode Is a method in Java.lang.Object unique code
If two objects are equal according to the equals(Object) method, then calling the hashCode method on
each of the two objects must produce the same integer result. It is not required that if two objects are
unequal according to the equals(java.lang.Object) method, then calling the hashCode method on each of
the two objects must produce distinct integer results.
public int hashCode()
CharSequence --> A CharSequence is a readable sequence of characters. This interface provides
uniform, read-only access to many different kinds of character sequences.
To get the data in desired order to our constraint use comparable.
StringS=newString(abc);
S=S+d;
NowS=abcd,

11
String
String is immutable.any value assigned cannot be
altered. Simply stated, objects of type String are
read only and immutable.
Instantiation slower comparatively to a
stringBuffer
String
class is used to manipulate character strings that
cannot be changed.

StringBuffer
StringBuffer grows.it is a growable array of
string /characters.
Instantiation is faster than a string.

String Buffer
String Buffer is Synchronized

String Builder
String Builder is not Synchronized,
Performance is better than string buffer

The StringBuffer class is used to represent


characters that can be modified.

Public static void main ( String a[ ] ) { }


If used as Private static void main(in[] arg) { } --> 2 errors
1. runtime error as main is declared private
2. java by default takes arg as string args which is a class ,no datatype allowed.
Public access modifier
Static no need to create instance for the main method
Void no arguments
Main( ) 1st method invoked by JVM.
String a[ ] command-line arguments as string arguments.
If command line arguments not given taken as empty not null
To execute a set of code before creating object / main() put it as below
static { //executable code need to get executed before creating object for the class }
Condition statements if.
Iteration(Looping) while, do-while, for.
Jump statements break, continue, return.
System.out.println( )
System a class in Java.Lang package.
Out Static object reference of printstream class of java.io package.
Println( ) a method in printstream class.

String Class methods


CharAt() ; getChars() , toCharArray() , equals() ,equalsIgnoreCase() , equalsUpperCase()
,equalsLowerCase() , regionMatches() , compareTo(), indexOf(), lastIndexOf() , substring() , concat() ,
replace() ,trim() , getBytes()
StringBuffer Class Methods
Length() , Capacity() ,ensureCapacity() , setLength() , charAt(), setCharAt() ,getChars(), append(),
insert(), reverse(), delete(), deleteCharAt(), replace(), subString()
String s=new String()
String(String s1)
String(StringBuffer s2) // will be executed faster than the previous one.
subString( ) - creates a copy of the string & a substring is generated from that copy.

12

Exception: A Condition that transfer a java program from a thrower to a catcher.


Information is passed as Exception or error object.
Throwable
1. Exceptions
2. errors.
Compile time exception (Checked exception): --> exceptions part of java.Lang Package.
--> Happens as the case of compile time
--> handled by java directly.
Example : classNotfoundException.
FileNotFoundException.
InterruptedException.
Runtime Exception ( Unchecked exception)

--> handled by Programmer / User.


--> exceptions occur at run time.
--> Belong to system as a whole.may be case of wrong Input.
Example : Runtime Exception.
NumberFormatException
StringIndexOutOfBoundsException
ArrayIndexOutOfBoundsException.
Occurence Of NullPointerException
If a Method has 6 Parameters , If I pass 5 parameters at runtime ,it gives nullPointer Exception.
Super class of Exception --> java.lang.Throwable
Key Words in Exception : try , Catch , finally, throw, throws, Exception.
Display exception to USER --> exception.printStackTrace();
Try catch finally
try {
// condition to check and the executable logic / code will be given here.
}
catch (Exception e) {
The exception is caught here
}
finally {
// Must execute things like closing a connection / statement will be given here.
// A try must be followed with catch or finally blocks.
}
try {

System.exit(0); // deny finally to execute. // normal termination of execution


// System.exit(non ZERO); Abnormal termination of condition.

}
try{
// Executable code
}
catch(Exception e) { }
catch(Exception e) { } // code will not be executed since Exception already caught.
catch(Exception e) { }
for throw

13
static int divide(int first,int second) throws MyException{
if(second==0) {
throw new MyException("can't be divided by zero");
} return first/second;
}
execution from a thrower to a catcher.
Throw
Throws
Declared with a reference name inside a
declared along with a class / method.
method.
Statement below throw will not be executed.
Exception is caught and is displayed to user.
Only one exception can be given at a time
Multiple exceptions can be declared.
Try - catch compulsory
Try catch optional.
Support both checked and unchecked
Support only checked exception
exceptions
Error
Exception
Errors can be caught at the time of execution
exception is a condition that transfer program
of a program.
Checked and unchecked exceptions are there.
Syntax & logical errors are there.
user-defined exception.
Class user_defined_exception extends exception { // desired code in exception }
Application Exception : Exceptions that are directly thrown to client.
public class InvocationTargetException extends Exception
public class UndeclaredThrowableException extends RuntimeException
Difference between comparable() and comparator()
Comparable
shows that the class knows how to
compare ITSELF against another class

Comparator interface
allows a single class know how to compare two
classes which (typically) are not the same type as
the comparator.

THREADING
THREAD A Set of sequential instructions that run independently of one another yet can directly
share resources with other threads.
Create instance of a thread or thread sub class invoke start() on instance.
3 Phases of Thread prebirth ,life , death.
Ways to use Thread
1. Extend the Java.Lang.Thread Subclass
Class myThread extends Thread { }
2. Implement the Runnable interface
public interface Runnable {
abstract public void run();
}
Make use of it
Animation happy = new Animation("Mr. Happy");
Thread myThread = new Thread( happy );
myThread.start();
Threads Execution time
A Thread continues to execute until one of the following things happens:

14
It returns from its target run() method
It's interrupted by an uncaught exception
Its stop() method is called
So what happens if the run() method for a thread never terminates, and the application that
started the thread never calls its stop() method?
The answer is that the thread lives on, even after the application that created it has finished. This
means we have to be aware of how our threads eventually terminate, or an application can end up
leaving orphaned threads that unnecessarily consume resources.
Thread
Processes
takes same workspace for executing different
takes separate workspace for executing
operations with different data.
different data.
Error and Exception
An error is an irrecoverable condition occurring at runtime. Such as OutOfMemory error. These JVM
errors and you cannot repair them at runtime.Though error can be caught in catch block but the
execution of application will come to a halt and is not recoverable.
While exceptions are conditions that occur because of bad input etc. e.g. FileNotFoundException will be
thrown if the specified file does not exist. Or a NullPointerException will take place if you try using a null
reference. In most of the cases it is possible to recover from an exception (probably by giving user a
feedback for entering proper values etc.)
Thread synchronization -->different threads take proper turns while using shared resources.
Monitor set of code blocks marked, one thread at a time, a protected portion of code enforce one
thread at a time policy.
Static Synchronized --> thread obtain lock on the class object.
Yield( ) --> provide maximum chances for other threads to run.
Thread States in Yield runnable, running, waiting , dead.
Thread Class , Runnable Interface --> extends a thread using either thread class or
implementing runnable interface.
Public void run() { }
// Create the object with the run() method
Runnable runnable = new BasicThread2();
// Create the thread supplying it with the runnable object
Thread thread = new Thread(runnable);
// Start the thread
thread.start();
Thread Properties
--> thread can voluntarily relinquish control
--> Preempted by higher priority thread.
Priorities of thread:
MIN_PRIORITY = 1
NORM_PRIORITY = 5
MAX_PRIORITY = 10
DAEMON THREAD : Daemon threads are service providers for other threads running in the same
process as the daemon thread.
call the setDaemon() method with the argument true
check isDaemon() that returns true or false to check if the thread is a daemon thread or not.
Example for Daemon thread : Garbage Collector.
After all threads complete execution ,Daemon thread will execute.

15
Sleep()
The time defined for a thread to stop
temporarily from execution will be kept till
the time completes and on any cause the
thread will be allowed to get executed.
For example say a thread given time 600ms to
execute it takes only 400ms then that
200mscantbeutilized.

wait( )
The time defined in milliseconds will not be
kept till the end.If needed the thread is got
back to execution b using notify() or notifyAll()
methods.
Here in this case the time taken [say 200ms in
sleep] can be utilized by either using
notify() or notifyall()

Notify()
'notify' wakes up a single thread waiting on the
object and passes the control of the monitor to
it.

NotifAll()
notifyAll wakes up a larger candidate pool of
threads - any of those threads that are notified
are candidates to enter the 'running' state.

Methods in a thread class


Final Boolean isAlive()
Final void join()
Final void setPriority(int level) { }
Final void notify()
Final void notifyAll()
Final void suspend()
Final void resume()
Thread states --> Start() , ready() , sleep() , wait() , stop()
Class abc { // int a; --> not a static variable, cantbeaccessedbymainmethod.
Synchronization
Synchronization among threads in Java is to serialize their access to some resource, namely an
object. Synchronization makes sure only one thread at a time can perform certain activities that
manipulate an object. In Java, every object has a lock associated with it. To be more specific, every class
and every instance of a class has its own lock. The synchronized keyword marks places where a thread
must acquire the lock before proceeding.
Example
class SpreadSheet {
int cellA1, cellA2, cellA3;
synchronized int sumRow() {
return cellA1 + cellA2 + cellA3;
}
synchronized void setRow( int a1, int a2, int a3 ) {
cellA1 = a1;
cellA2 = a2;
cellA3 = a3;
}
...
}
ThreadGroup
A ThreadGroup is used to represent a group of Threads. A tree structure can be formed from
ThreadsGroups containing other ThreadGroups. Threads can only access the ThreadGroup to which they
belong. This means that access to a ThreadGroups parent or other ThreadGroup is not permitted. Once a
ThreadGroup is created various information can be obtained such as the ThreadGroups name, how many
threads are active, the maximum priority that can be contained within the group and a host of other
information.

16
The ThreadGroup class provides two constructors.
ThreadGroup(String name)
ThreadGroup(ThreadGroup parent, String name)
public class ThreadGroupTest{
public static void main(String[] args){
ThreadGroup squares = new ThreadGroup("Squares");
Thread t1 = new Thread(squares, new T(), "t1");
Thread t2 = new Thread(squares, new T(), "t2");
t1.start();
t2.start();
System.out.println("ThreadGroup name is: " + squares.getName());
System.out.println("There are currently " + squares.activeCount() + " threads running");
System.out.println("The maximum priority of a Thread that can be contained
within " + squares.getName() + " is " + squares.getMaxPriority());
System.out.println("There are currently " + squares.activeGroupCount() + " active groups");
System.out.println(squares.getName() + " parent is " + squares.getParent());
}
}
class T implements Runnable{
private int square;
public void run(){
for(int i = 1; i < 5; i++){
square = i * i;
System.out.println("Thread" + Thread.currentThread().getName()+" has a priority of " +
Thread.currentThread().getPriority() +
": " + square);
}
}
}
what will happen if i set it as setPriority(100000000)?
Exception in thread "main" java.lang.IllegalArgumentException
at java.lang.Thread.setPriority(Unknown Source)
at com.wellpoint.common.eis.edirouter.utils.XmlHelper.main(XmlHelper.java:1325)
Cloning in Java
Java supports two type of cloning: - Deep and shallow cloning. By default shallow copy is used in
Java. Object class has a method clone() which does shallow cloning.
In shallow copy the object is copied without its contained objects.
Shallow clone only copies the top level structure of the object not the lower levels.
It is an exact bit copy of all the attributes.
Figure 1: Original java object obj

17
The shallow copy is done for obj and new object obj1 is created but contained objects of obj are not
copied.

Figure 2: Shallow copy object obj1


It can be seen that no new objects are created for obj1 and it is referring to the same old contained
objects. If either of the containedObj contain any other object no new reference is created
Characteristic:
If we do a = clone(b)
1) Then b.equals(a)
2) No method of a can modify the value of b.
Deep Cloning
Ans) In deep copy the object is copied along with the objects it refers to.
Deep clone copies all the levels of the object

Figure 3 : Original Object obj


When a deep copy of the object is done new references are created.

Figure 4: obj2 is deep copy of obj1


One solution is to simply implement your own custom method (e.g., deepCopy()) that returns a deep
copy of an instance of one of your classes. This may be the best solution if you need a complex mixture
of deep and shallow copies for different fields, but has a few significant drawbacks:
You must be able to modify the class (i.e., have the source code) or implement a subclass. If you have a
third-party class for which you do not have the source and which is marked final, you are out of luck.

18
Youmustbeabletoaccessallofthefieldsoftheclassssuperclasses.Ifsignificantpartsoftheobjects
state are contained in private fields of a superclass, you will not be able to access them.
You must have a way to make copies of instances of all of the other kinds of objects that the object
references. This is particularly problematic if the exact classes of referenced objects cannot be known
until runtime.
Custom deep copy methods are tedious to implement, easy to get wrong, and difficult to maintain. The
method must be revisited any time a change is made to the class or to any of its superclasses.
Other common solution to the deep copy problem is to use Java Object Serialization (JOS). The idea is
simple:WritetheobjecttoanarrayusingJOSsObjectOutputStreamandthenuse
ObjectInputStream to reconsistute a copy of the object. The result will be a completely distinct object,
with completely distinct referenced objects. JOS takes care of all of the details:
superclass fields, following object graphs, and handling repeated references to the same object within the
graph.
It will only work when the object being copied, as well as all of the other objects references directly or
indirectly by the object, are serializable. (In other words, they must implement java.io.Serializable.)
Fortunately it is often sufficient to simply declare that a given class implements java.io.Serializable and let
Javasdefaultserialization mechanisms do their thing. Java Object Serialization is slow, and using it to
make a deep copy requires both serializing and deserializing.
There are ways to speed it up (e.g., by pre-computing serial version ids and defining custom
readObject() and writeObject() methods), but this will usually be the primary bottleneck. The byte array
stream implementations included in the java.io package are designed to be general enough to perform
reasonable well for data of different sizes and to be safe to use in a multi-threaded environment. These
characteristics, however, slow down ByteArrayOutputStream and (to a lesser extent)
ByteArrayInputStream .
Difference Between the two
Ans) The differences are as follows:
Consider the class:
public class MyData{
String id;
Map myData;
}
TheshallowcopyingofthisobjectwillhavenewidobjectandvaluesasbutwillpointtothemyDataof
the original object. So a change in myData by either original or cloned object will be reflected in other
also. But in deep copying there will be new id object and also new myData object and independent of
original object but with same values.
Shallow copying is default cloning in Java which can be achieved using clone() method of Object class.
For deep copying some extra logic need to be provided.
Disadvantages:
Ans) Disadvantages of using Serialization to achieve deep cloning
Serialization is more expensive than using object.clone().
Not all objects are serializable.
Serialization is not simple to implement for deep cloned object..
constructor call on Deserialization
During deserialization, the fields of non-serializable classes will be initialized using the public or protected
no-arg constructor of the class. A no-arg constructor must be accessible to the subclass that is
serializable. The fields of serializable subclasses will be restored from the stream.
By default, only one ResultSet object per Statement object can be open at the same time. Therefore, if
the reading of one ResultSet object is interleaved with the reading of another, each must have been

19
generated by different Statement objects. All execution methods in the Statement interface implicitly
close a statment's current ResultSet object if an open one exists.
A stored procedure can process related data and return multiple result sets, this way may save fewer
calls to database server. You need to include code to retrieve the result sets, Java JDBC Statement
provide the getResultSet method to retrieve each result set. You can access the first result set by calling
the getResultSet method on your Statement object. In a loop, position the cursor using the next method,
and retrieve data from each column of the current row of the ResultSet object using getXXX methods. To
determine if more result sets are available, you can call the getMoreResults method in Statement, which
returns a boolean value of true if more result sets are available. If more result sets are available, you can
call the getResultSet method again to access them, continuing the process until all result sets have been
processed. If the getMoreResults method returns false, there are no more result sets to process. Calling
getMoreResults() implicitly closes any previously returned ResultSet object(s) from method getResultSet.
In the following example, an open connection to the Database SQL Server is passed in to the function,
and the stored procedure is returns n result sets:
public static void executeProcedure(Connection con) {
try {
CallableStatement stmt = con.prepareCall(...);
..... //Set call parameters, if you have IN,OUT, or IN/OUT parameters
boolean results = stmt.execute();
int rsCount = 0;
//Loop through the available result sets.
while (results) {
ResultSet rs = stmt.getResultSet();
//Retrieve data from the result set.
while (rs.next()) {
....// using rs.getxxx() method to retieve data
}
rs.close();
//Check for next result set
results = stmt.getMoreResults();
}
stmt.close();

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

}
When you make the call to the getMoreResults() method of the Statement class, the previously returned
result set is implicitly closed. How to keep result sets open when you check the next availiable result set.
You can call the one with a parameter getMoreResults(int current) method. The parameter current
indicates what should happen to current ResultSet objects obtained using the method getResultSet. You
can specify one of these constants:
Statement.KEEP_CURRENT_RESULT : Checks for the next ResultSet, but does not close the current
ResultSet.
Statement.CLOSE_CURRENT_RESULT : Checks for the next ResultSet, and closes the current ResultSet.
Statement.CLOSE_ALL_RESULTS : Closes all ResultSets that were previously kept open
GARBGAGE COLLECTION

20
When a object or method or variable is no longer needed the memory space allocated will be
garbage collected and is made available for reuse.
JavadoesntguaranteewhenGarbagecollectorwillbecalled.
I t can be called in 4 ways as
1. Automatic call by compiler
2. System.gc();
3. Protected void finalize() { }
4. use java.lang.ref.Reference.clear() to force Garbage collection to happen.
can a for loop be garbage collected?
The memory occupied by for loop is garbage collected. I mean for eg. you decl a variable i and
increment the value. that i occupy some memory that memory is garbage collected. JVM is responsible
for calling garbage collector garbage collector is a deamon thread.
Java.lang.ref A object is reclaimed or recreated is made available for reuse.
use java.lang.ref.Reference.get() to reclaim the object that is enqued for gc
[ for Detailed Description see below]
Java.Lang.Ref HIERARCHY Classes
public abstract class Reference extends Object class defines the operations common to all reference
objects

Methods in Reference
public void clear() --> Clears this reference object
public boolean enqueue() --> Adds this reference object to the queue with which it is
registered
public Object get() --> Returns this reference object's referent.
Public boolean isEnqueued() --> Tells whether or not this reference object has been
enqueued, either by the program or by the garbage collector
public class ReferenceQueue extends Object --> to which registered reference objects are appended by
the garbage collector after the appropriate reachability changes are detected.
Methods in ReferenceQueue
public Reference poll( ) --> Polls this queue to see if a reference object is available, returning one
immediately if so.
public Reference remove( long timeout) --> Removes the next reference object in this
queue, blocking until either one becomes available or the given timeout period expires.
public Reference remove( ) --> Removes the next reference object in this queue, blocking until one
becomes available.
public class SoftReference extends Reference --> Soft reference objects, which are cleared at the
discretion of the garbage collector in response to memory demand. Soft references are most often used
to implement memory-sensitive caches.
Constructors in SoftReference.
SoftReference(Object referent)--> Creates a new soft reference that refers to the given object.

21
SoftReference(Object referent, ReferenceQueue q) --> Creates a new soft reference that refers to the
given object and is registered with the given queue.
PhantomReference extends Reference which are enqueued after the collector determines
that their referents may otherwise be reclaimed.
Methods in SoftReference
Public Reference get() --> Returns this reference object's referent.
public class WeakReference extends Reference --> Weak reference objects, which do not prevent their
referents from being made finalizable, finalized, and then reclaimed. Weak references are most often
used to implement canonicalizing mappings.
Constructors --> SoftReference(Object referent),
SoftReference(Object referent, ReferenceQueue q)
Java.Lang.Reflect Classes
public class AccessibleObject extends Object --> base class for Field, Method and Constructor objects. It
provides the ability to flag a reflected object as suppressing default Java language access control checks
when it is used. The access checks--for public, default (package) access, protected, and private
members--are performed when Fields, Methods or Constructors are used to set or get fields, to invoke
methods, or to create and initialize new instances of classes, respectively
Constructor protected AccessibleObject() --> used by the Java Virtual Machine.
Methods in AccessibleObject
public static void setAccessible(AccessibleObject[] array,boolean flag) throws SecurityException -->
Convenience method to set the accessible flag for an array of objects with a single security check (for
efficiency).
public void setAccessible(boolean flag)throws SecurityException --> Set the accessible flag for this object
to the indicated boolean value. A value of true indicates that the reflected object should suppress Java
language access checking when it is used. A value of false indicates that the reflected object should
enforce Java language access checks
public boolean isAccessible() --> Get the value of the accessible flag for this object.
public final class Array extends Object
public static Object newI nstance(Class componentType,int length)throws
NegativeArraySizeException --> Creates a new array with the specified component type and length.
public static Object newInstance(Class componentType, int[] dimensions)
throws IllegalArgumentException, NegativeArraySizeException
--> Creates a new array with the specified component type and dimensions
--> componentType - the Class object representing the component type of the new array
--> dimensions - an array of int types representing the dimensions of the new array
public static int getLength(Object array) --> Returns the length of the specified array object, as an int.
public static Object get(Object array,int index) --> Returns the value of the indexed component in the
specified array object.
The value is automatically wrapped in an object if it has a primitive type.
public static boolean getBoolean(Object array,int index) --> Returns the value of the indexed component
in the specified array object, as boolean.
Similarly getByte(), getChar()getShort(),getInt(),getLong(), getFloat(),getDouble(),
public static void set(Object array, int index, Object value)

22
--> Sets the value of the indexed component of the specified array object to the specified new value. The
new value is first automatically unwrapped if the array has a primitive component type.
public static void setBoolean(Object array, int index, boolean z)
--> Sets the value of the indexed component of the specified array object to the specified boolean value.
Similarly setByte(),setChar(),setShort(),setInt(),setLong(),setFloat(), setDouble().
public final class Constructor extends AccessibleObject implements Member --> Constructor provides
information about, and access to, a single constructor for a class.
public Class getDeclaringClass() -->
public String getName()--> Return Constructor name
public int getModifiers()--> Java language modifiers for the constructor represented by this
Constructor object, as an integer to decode modifiers
public Class[] getParameterTypes()--> array of Class objects that represent the formal parameter types,
in declaration order,length 0 refer no parameter.
public Class[] getExceptionTypes()--> Returns an array of Class objects that represent the types of of
exceptions declared to be thrown by the underlying constructor represented by this Constructor object.
public boolean equals(Object obj)--> comapares this Constructor against the specified object.
public int hashCode() --> returns hash code for constructor
public String toString()--> Returns a string describing this Constructor.
public Object newInstance(Object[] initargs) --> represented by this Constructor object to create and
initialize a new instance of the constructor's declaring class, with the specified initialization parameters.
public final class Method extends AccessibleObject implements Member method provides information
about, and access to, a single method on a class or interface
equals(Object obj) --> Compares this Method against the specified object
getDeclaringClass()--> Returns the Class object representing the class or interface that declares the
method represented by this Method object.
getExceptionTypes()--> Returns an array of Class objects that represent the types of the exceptions
declared to be thrown
getModifiers() --> Java language modifiers for the method represented by this Method object, as an
integer.
getName()--> Returns the name of the method represented by this Method object, as a String.
getParameterTypes()--> Returns an array of Class objects that represent the formal parameter types, in
declaration order, of the method represented by this Method object.
getReturnType()--> Returns a Class object that represents the formal return type of the method
represented by this Method object.
hashCode() --> Returns a hashcode for this Method.
invoke(Object obj, Object[ ] args)--> Invokes the underlying method represented by this Method object,
on the specified object with the specified parameters.

23

toString()--> Returns a string describing this Method.


public class Modifier extends Object --> provides static methods and constants to decode class and
member access modifiers Fields
Public static int ABSTRACT --> representing the abstract modifier.
Public static int FINAL --> representing the final modifier.
Public static int INTERFACE --> representing the interface modifier
Public static int NATIVE --> representing the native modifier.
Public static int PRIVATE --> representing the private modifier.
Public static int PROTECTED --> representing the protected modifier
Public static int STATIC--> representing the static modifier.
Public static int STRICT --> representing the strictfp modifier.
Public static int SYNCHRONIZED --> representing the synchronized modifier.
Public static int TRANSIENT --> representing the transient modifier.
Public static int VOLATILE --> representing the volatile modifier
Methods returns true
isAbstract(int mod) --> specifier integer includes the abstract modifier
isFinal(int mod) --> specified integer includes the final modifier.
isI nterface(int mod)--> specifier integer includes the interface modifier
isNative(int mod) --> specifier integer includes the native modifier.
isPrivate(int mod) --> specifier integer includes the private modifier
isProtected(int mod)--> specifier integer includes the protected modifier.
isPublic(int mod)--> specified integer includes the public modifier.
isStatic(int mod)--> specifier integer includes the static modifier.
isStrict(int mod)--> specifier integer includes the strictfp modifier.
isTransient(int mod)--> specifier integer includes the transient modifier
isVolatile(int mod)--> specified integer includes the volatile modifier.
toString(int mod)--> Return a string, access modifier flags in the specified modifier
public class Proxy extends Object implements Serializable
--> Proxy provides static methods for creating dynamic proxy classes and instances, and it is also the
superclass of all dynamic proxy classes created by those methods.
getI nvocationHandler(Object proxy) --> Returns the invocation handler for the specified
proxy instance getProxyClass(ClassLoader loader, Class[] interfaces)--> Returns the java.lang.Class
object for a proxy class given a class loader and an array of interfaces.
isProxyClass(Class cl)--> Returns true if and only if the specified class was dynamically generated to be a
proxy class using the getProxyClass method or the newProxyInstance method.
newProxyI nstance(ClassLoader loader,Class[] interfaces, InvocationHandler h) --> Returns an instance
of a proxy class for the specified interfaces that dispatches method invocations to the specified invocation
handler.
public final class ReflectPermission extends BasicPermission
Constructor --> public ReflectPermission(String name)
Methods are inherited from java.security.BasicPermission --> equals, getActions, hashCode, implies,
newPermissionCollection
java.security.Permission --> checkGuard, getName, toString
class java.lang.Object --> clone, finalize, getClass, notify, notifyAll, wait
Interfaces in Java.Lang.Reflect
public interface I nvocationHandler Methods
public Object invoke(Object proxy,Method method, Object[] args)

24
throws Throwable --> Processes a method invocation on a proxy instance and returns the result. This
method will be invoked on an invocation handler when a method is invoked on a proxy instance that it is
associated with.
public interface Member --> Member is an interface that reflects identifying information about a single
member (a field or a method) or a constructor.
Methods
getDeclaringClass() --> Returns the Class object representing the class or interface that declares the
member or constructor represented by this Member.
getModifiers() --> Returns the Java language modifiers for the member or constructor represented by
this Member, as an integer
getName() --> Returns the simple name of the underlying member or constructor
represented by this Member
JAVA.IO PACKAGE
Byte Streams handle I/O of raw binary data.
FileInputStream
FileOutputStream
Example
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class CopyBytes {
public static void main(String[] args) throws IOException {
FileInputStream in = null;
FileOutputStream out = null;
try {
in = new FileInputStream("xanadu.txt");
out = new FileOutputStream("outagain.txt");
int c;
while ((c = in.read()) != -1) {
out.write(c);
}
} finally {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
}
}
}
Character Streams handle I/O of character data, automatically handling translation to and from the
local character set.
All character
stream classes are descended from Reader and Writer. As with byte streams, there are character stream
classes that specialize in file I/O: FileReader and FileWriter. The
import java.io.FileReader;

25
import java.io.FileWriter;
import java.io.IOException;
public class CopyCharacters {
public static void main(String[] args) throws IOException {
FileReader inputStream = null;
FileWriter outputStream = null;
try {
inputStream = new FileReader("xanadu.txt");
outputStream = new FileWriter("characteroutput.txt");
int c;
while ((c = inputStream.read()) != -1) {
outputStream.write(c);
}
} finally {
if (inputStream != null) {
inputStream.close();
}
if (outputStream != null) {
outputStream.close();
}
}

}
}
CopyCharacters is very similar to CopyBytes. The most important difference is that CopyCharacters uses
FileReader and FileWriter for input and output in place of FileInputStream and FileOutputStream
Buffered Streams optimize input and output by reducing the number of calls to the native API.
Buffered input streams read data from a memory area known as a buffer; the native input API is called
only when the buffer is empty. Similarly, buffered output streams write data to a buffer, and the native
output API is called only when the buffer is full.
inputStream = new BufferedReader(new FileReader("xanadu.txt"));
outputStream =new BufferedWriter(new fileWriter("characteroutput.txt"));
It often makes sense to write out a buffer at critical points, without waiting for it to fill. This is
known as flushing the buffer.
Some
buffered output classes support autoflush, specified by an optional constructor argument. When autoflush
is enabled, certain key events cause the buffer to be flushed. For example, an autoflush PrintWriter
object flushes the buffer on every invocation of println or format. See Formatting for more on these
methods.
To flush a stream manually, invoke its flush
method. The flush method is valid on any output stream, but has no effect unless the stream is buffered.
Data Streams handle binary I/O of primitive data type and String values. Data streams support
binary I/O of primitive data type values (boolean, char, byte, short, int, long, float, and double) as well as
String values. All data streams implement either the DataInput interface or the DataOutput interface.
The program defines some constants containing the name of the data file and the data that will be
written to it:
static final String dataFile = "invoicedata";
static final double[] prices = { 19.99, 9.99, 15.99, 3.99, 4.99 };
static final int[] units = { 12, 8, 13, 29, 50 };

26
static final String[] descs = { "Java T-shirt",
"Java Mug", "Duke Juggling Dolls", "Java Pin", "Java Key Chain" };
Then DataStreams opens an output stream. Since a DataOutputStream can only be created as a wrapper
for an existing byte stream object, DataStreams provides a buffered file output byte stream.
out = new DataOutputStream(new
BufferedOutputStream(new FileOutputStream(dataFile)));
DataStreams writes out the records and closes the output stream.
for (int i = 0; i < prices.length; i ++) {
out.writeDouble(prices[i]);
out.writeInt(units[i]);
out.writeUTF(descs[i]);
}
The writeUTF method writes out String values in a modified form of UTF-8. This is a variable-width
character encoding that only needs a single byte for common Western characters.
Now DataStreams reads the data back in again. First it must provide an input stream, and variables to
hold the input data. Like DataOutputStream, DataInputStream must be constructed as a wrapper for a
byte stream.
in = new DataInputStream(new BufferedInputStream(new FileInputStream(dataFile)));
double price;
int unit;
String desc;
double total = 0.0;
Now DataStreams can read each record in the stream, reporting on the data it encounters.
try {
while (true) {
price = in.readDouble();
unit = in.readInt();
desc = in.readUTF();
System.out.format("You ordered %d units of %s at $%.2f%n",
unit, desc, price);
total += unit * price;
}
} catch (EOFException e) { }
Notice that DataStreams detects an end-of-file condition by catching EOFException, instead of testing for
an invalid return value
Object Streams handle binary I/O of objects.
The object stream classes are ObjectInputStream and ObjectOutputStream.
These classes implement ObjectInput and ObjectOutput, which are subinterfaces of DataInput and
DataOutput. If readObject() doesn't return the object type expected, attempting to cast it to the correct
type may throw a ClassNotFoundException.
Object ob = new Object();
out.writeObject(ob);
out.writeObject(ob);
Each
writeObject has to be matched by a readObject, so the code that reads the stream back will look
something like this:
Object ob1 = in.readObject();
Object ob2 = in.readObject();
This results in two variables, ob1 and ob2, that are references to a single object.

27
Read a character from a keyboard / file.
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
fileInputStreamReader fin = new FileInputStreamReader();
br.load(fin);
write a character into a file
BufferedReader br = new BufferedReader(new OutputStreamReader(System.in));
fileOutputStreamReader fout = new FileOutputStreamReader();
br.store(fout);
to read a character from Keyboard
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
br.readLine();
Return null when ends in EOF of File.
TO UPLOAD & DOWNLOAD A FILE USING JAVA.IO.FILE.
package com.resource.util;
import
import
import
import
import
import
import
import
import

java.io.BufferedInputStream;
java.io.BufferedOutputStream;
java.io.File;
java.io.FileInputStream;
java.io.FileOutputStream;
java.io.IOException;
java.net.MalformedURLException;
java.net.URL;
java.net.URLConnection;

public class FileUpload


{
public void upload( String ftpServer, String user, String password,
String fileName, File source ) throws MalformedURLException,
IOException
{
if (ftpServer != null && fileName != null && source != null){
StringBuffer sb = new StringBuffer( "ftp://" );
// check for authentication else assume its anonymous access.
if (user != null && password != null) {
sb.append( user );
sb.append( ':' );
sb.append( password );
sb.append( '@' );
}
sb.append( ftpServer );
sb.append( '/' );
sb.append( fileName );
sb.append( ";type=i" );
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
try {
URL url = new URL( sb.toString() );
URLConnection urlc = url.openConnection();
bos = new BufferedOutputStream( urlc.getOutputStream());

28
bis = new BufferedInputStream( new FileInputStream( source ));
int i;
// read byte by byte until end of stream
while ((i = bis.read()) != -1) {
bos.write( i );
}
}
Finally {
if (bis != null)
try {
bis.close(); }
catch (IOException ioe) {
ioe.printStackTrace();
}
if (bos != null)
try {
bos.close();
}
catch (IOException ioe) {
ioe.printStackTrace();
}
}
}
Else {
System.out.println( "Input not available." );
}
}
public void download( String ftpServer, String user, String password,String fileName, File destination )
throws MalformedURLException,IOException {
if (ftpServer != null && fileName != null && destination != null) {
StringBuffer sb = new StringBuffer( "ftp://" );
// check for authentication else assume its anonymous access.
if (user != null && password != null) {
sb.append( user );
sb.append( ':' );
sb.append( password );
sb.append( '@' );
}
sb.append( ftpServer );
sb.append( '/' );
sb.append( fileName );
/*
* type ==> a=ASCII mode, i=image (binary) mode, d= file
* directory listing */
sb.append( ";type=i" );
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
try
{
URL url = new URL( sb.toString());
URLConnection urlc = url.openConnection();

29
bis = new BufferedInputStream( urlc.getInputStream() );
bos = new BufferedOutputStream( new FileOutputStream(
destination.getName()));
int i;
while ((i = bis.read()) != -1) {
bos.write( i ); } }
finally {
if (bis != null)
try {
bis.close();
}
catch (IOException ioe) {
ioe.printStackTrace(); }
if (bos != null)
try {
bos.close();
}
catch (IOException ioe) {
ioe.printStackTrace();
}
}
}
else {
System.out.println( "Input not available" );
}
}
}
Properties of a bean
All variables are private.
All methods are public.
If a variable is declared public it can be globally accessed.
Will have set() and get() methods
Serializable - java.io.serializable
It is an [empty method] Marker interface
Writes the state of the object into byte stream.
Allow automatic typecasting.
DoesntsupportTransientandstatic.
Base fields alone are handled if the base class implements serializable.
Used or always Refer to Dynamic Contents.
serialization is the process of saving an object's state to a sequence of bytes, as well as the process of
rebuilding those bytes into a live object at some future time.
Object is persistent.
Externizable --> provide additional control for object that write into a byte stream
Public void readExternal(objectInput OI) throws IOEXception--> write primitive data
Public void writeExternal(objectOutput OO) throws IOException
JAVA.UTIL.PACKAGE PACKAGE HIERARCHY.
AbstractCollection

30
--> AbstractSequentialList
--> LinkedList
--> AbstractList
--> ArrayList
--> Vector --> Stack
--> AbstractSet
--> HashSet
--> LinkedHashSet
--> TreeSet
--> AbstractMap
--> HashMap
--> LinkedHashMap
--> IdentityHashMap
--> TreeMap
--> weakHashMap
--> Arrays
--> BitSet
--> Calender
--> Georgian Calender
--> Collections
--> Concurrency
--> Date
--> Dictionary
--> HashTable
--> Propeties
--> EventListenerProxy
--> EventObject
--> Locale
--> Observable
--> Permission
--> BasicPermission
--> PropertyPermission
--> Random
--> ResourceBundle
--> ListResourceBundle
--> PropertyResourceBundle
--> StringTokenizier
--> Timer
--> TimerTask
--> TimeZone
--> SmpleTimeZone
Interface Hierarchy
--> Collection
--> List
--> Set
--> SortedSet
--> Comparator
--> Enumeration
--> Eventistener
--> Iterator
--> ListIterator
--> Map

31
--> SortedMap
--> Map.Entry
--> Observer
--> RandomAccess.
BASIC DIFFERENCES
Vector
Initial Size = 10; Will double its size while
growing [if Size=100 increase to 200 from
200 to 400 ]
Synchronized
Automatic type casting is allowed
Contain Legacy(built-in) methods
that are not part of collections f/w.
Poor Performance
HashMap
Not synchronized
Allow duplicates and null key/null
values
No order maintained.
Best performance.
Collections Class
Not Synchronized
Iterator can be used.
Best Performance
Iterator
Uni Directional
Hasnext()
Next();
Remove()
Used in ArrayList
HashMap
No order Maintained
1 null Key 2null values Allowed
List having mechanism access should be the
same
List
Allow Duplicates
Index based Access
Enumeration
Enumeration contains 2 methods namely
hasMoreElements() & nextElement().
Using remove() its possible to delete
objects.
Enumeration deals with objects
Can modify collection Objects.
Part of legacy classes

ArrayList
Initial size need not be defined. Grow in 2/3rd of its
size [ If size=100 increase to 150 then 225 etc]
Not synchronized
Doesntallowautomatictypecasting
Doesnthaveandlegacymethods.
Best Performance
HashTable
synchronized
doesntallowduplicates,nullkey/nullvalues
data is hashed and stored and maintained in order.
Poor Performance.
Legacy Class
Synchronized
Enumeration can be used.
Poor Performance.
ListIterator
BiDirectional
Hasnext();
Next()
Remove()
hasPrevoius()
previous()
Used in LinkedList.
TreeMap
Default sort
No Null Key / null Value allowed
Fast Access
Map
No duplicates allowed
Key based access
Iterator
Iterator contains three methods namely hasNext(),
next(),remove().
Not supported to delete objects with Iterator
iteration deals with values only
Not Possible.
Part of Collections class.
iterator is fail-safe. iterator to go through a
collection you can be sure of no concurrent
modifications in the underlying collection which may
happen in multi-threaded environments.

32
Enumeration is not fail safe.
HashSet
The underlying data structure is Hashtable
Heterogeneous objects are allowed
Insertion order is not preserved and it is
based on hashcode of the objects
null insertion is possible

iterator is a design pattern and the purpose is to


abstract looping.
TreeSet
The underlying data structure is balanced tree
Heterogeneous objects are not allowed bydefalut
Insertion order is not preserved and all the objects
are inserted according to some sorting order.
As the first element only null insertion is possible
and in all other cases we will get
NullPointerException

Some points about collection objects


List allow Duplicates
Set no duplicates
MAP key / Value Pair
Set Interface --> extends Collection.
-->DoesntallowDuplicates.
--> Order is not maintained.
--> add()
List

Map

--> allow Duplicates.


--> Order is maintained.
--> add(), addAll()
--> Interface.
--> Store key / value pairs
--> Values may be duplicated. Accept null key / null values.

HashMap

--> a Class implement Map ,has no specific methods


uses methods of map
--> example for Adapter class

Dictionary

--> Store key/value pairs.


-->Doesntallowduplicates.
--> Put(),get(),size(),isEmpty(),remove()

Property Methods
Tree Map

--> load() & store()

--> store key /value pairs


--> Stored in sorted order for rapid retrieval

SortedSet

--> asset that maintain its elements in Ascending order


First() last()
SortedMap --> A map that maintains its mappings in ascending key order.
Immediate Super class of vector and ArrayList AbstractList implements List
interface.
Example for Collection Objects
Vector

33
import java.util.*;
public class VectorDemo{
public static void main(String[] args){
Vector<Object> vector = new Vector<Object>();
int primitiveType = 10;
Integer wrapperType = new Integer(20);
String str = "tapan joshi";
vector.add(primitiveType);
vector.add(wrapperType);
vector.add(str);
vector.add(2, new Integer(30));
System.out.println("the elements of vector: " + vector);
System.out.println("The size of vector are: " + vector.size());
System.out.println("The elements at position 2 is: " + vector.elementAt(2));
System.out.println("The first element of vector is:"+ vector.firstElement());
System.out.println("The last element of vector is: " + vector.lastElement());
vector.removeElementAt(2);
Enumeration e=vector.elements();
System.out.println("The elements of vector: " + vector);
while(e.hasMoreElements()){
System.out.println("The elements are: " + e.nextElement());
}
}
}
ArrayList
import java.util.*;
public class ArrayListDemo{
public static void main(String[] args) {
ArrayList<Object> arl=new ArrayList<Object>();
Integer i1=new Integer(10);
Integer i2=new Integer(20);
Integer i3=new Integer(30);
Integer i4=new Integer(40);
String s1="tapan";
System.out.println("The content of arraylist is: " + arl);
System.out.println("The size of an arraylist is: " + arl.size());
arl.add(i1);
arl.add(i2);
arl.add(s1);
System.out.println("The content of arraylist is: " + arl);
System.out.println("The size of an arraylist is: " + arl.size());
arl.add(i1);
arl.add(i2);
arl.add(i3);
arl.add(i4);
Integer i5=new Integer(50);
arl.add(i5);
System.out.println("The content of arraylist is: " + arl);
System.out.println("The size of an arraylist is: " + arl.size());
arl.remove(3);
Object a=arl.clone();
System.out.println("The clone is: " + a);

34
System.out.println("The content of arraylist is: " + arl);
System.out.println("The size of an arraylist is: " + arl.size());
}
}
merge 2 Arraylist
ArrayList x = new ArrayList();
ArrayList y= new ArrayList();
x.add(a);
x.add(b);
x.add(c);
y.add(d);
for(int i=0; i<x.size; i++) {
System.outp.println(x.get());
} // for merging the values.
x.addAll(y);
Hashmap
import java.util.*;
class HashMapDemo {
public static void main(String args[]) {
// Create a hash map
HashMap hm = new HashMap();
// Put elements to the map
hm.put("John Doe", new Double(3434.34));
hm.put("Tom Smith", new Double(123.22));
hm.put("Jane Baker", new Double(1378.00));
hm.put("Todd Hall", new Double(99.22));
hm.put("Ralph Smith", new Double(-19.08));
// Get a set of the entries
Set set = hm.entrySet();
// Get an iterator
Iterator i = set.iterator();
// Display elements
while(i.hasNext()) {
Map.Entry me = (Map.Entry)i.next();
System.out.print(me.getKey() + ": ");
System.out.println(me.getValue());
}
System.out.println();
// Deposit 1000 into John Doe's account
double balance = ((Double)hm.get("John Doe")).doubleValue();
hm.put("John Doe", new Double(balance + 1000));
System.out.println("John Doe's new balance: " +
hm.get("John Doe"));
}
}
HashTable
import java.util.Hashtable;
import java.util.Vector;

35
import java.util.Collections;
import java.util.Enumeration;
public class SortHashtable {
public static void main(String[] args) {
// Create and populate hashtable
Hashtable ht = new Hashtable();
ht.put("ABC", "abc");
ht.put("XYZ", "xyz");
ht.put("MNO", "mno");
// Sort hashtable.
Vector v = new Vector(ht.keySet());
Collections.sort(v);
// Display (sorted) hashtable.
for (Enumeration e = v.elements(); e.hasMoreElements();) {
String key = (String)e.nextElement();
String val = (String)ht.get(key);
System.out.println("Key: " + key + "
Val: " + val);
}
}

}
TREEMAP
import java.util.*;
public class TreeMapExample{
public static void main(String[] args) {
System.out.println("Tree Map Example!\n");
TreeMap <Integer, String>tMap = new TreeMap<Integer, String>();
tMap.put(1, "Sunday");
tMap.put(2, "Monday");
tMap.put(3, "Tuesday");
tMap.put(4, "Wednesday");
tMap.put(5, "Thursday");
tMap.put(6, "Friday");
tMap.put(7, "Saturday");
System.out.println("Keys of tree map: " + tMap.keySet());
System.out.println("Values of tree map: " + tMap.values());
System.out.println("Key: 5 value: " + tMap.get(5)+ "\n");
System.out.println("First key: " + tMap.firstKey()+" Value: "+
tMap.get(tMap.firstKey())+ "\n");
System.out.println("Last key:" + tMap.lastKey() + " Value: "+
tMap.get(tMap.lastKey()) + "\n");
System.out.println("Removing first data:"+ tMap.remove(tMap.firstKey()));
System.out.println("Now the tree map Keys: " + tMap.keySet());
System.out.println("Now the tree map contain: " + tMap.values() + "\n");
System.out.println("Removing last data: " + tMap.remove(tMap.lastKey()));
System.out.println("Now the tree map Keys: " + tMap.keySet());
System.out.println("Now the tree map contain: " + tMap.values());
}
}
HashSet

36
import java.util.*;
public class CollectionTest {
public static void main(String [] args) {
System.out.println( "Collection Example!\n" );
int size;
// Create a collection
HashSet <String>collection = new HashSet <String>();
String str1 = "Yellow", str2 = "White", str3 = "Green", str4 = "Blue";
Iterator iterator;
//Adding data in the collection
collection.add(str1);
collection.add(str2);
collection.add(str3);
collection.add(str4);
System.out.print("Collection data: ");
//Create a iterator
iterator = collection.iterator();
while (iterator.hasNext()){
System.out.print(iterator.next() + " ");
}
System.out.println();
// Get size of a collection
size = collection.size();
if (collection.isEmpty()){
System.out.println("Collection is empty");
}
else{
System.out.println( "Collection size: " + size);
}
System.out.println();
// Remove specific data
collection.remove(str2);
System.out.println("After removing [" + str2 + "]\n");
System.out.print("Now collection data: ");
iterator = collection.iterator();
while (iterator.hasNext()){
System.out.print(iterator.next() + " ");
}
System.out.println();
size = collection.size();
System.out.println("Collection size: " + size + "\n");
//Collection empty
collection.clear();
size = collection.size();
if (collection.isEmpty()){
System.out.println("Collection is empty");
}
else{
System.out.println( "Collection size: " + size);
}
}
}

37

LINKEDHASHSET
import java.util.LinkedHashSet;
public class CopyElementsOfHashSetToArrayExample {
public static void main(String[] args) {
//create object of LinkedHashSet
LinkedHashSet lhashSet = new LinkedHashSet();
//add elements to LinkedHashSet object
lhashSet.add(new Integer("1"));
lhashSet.add(new Integer("2"));
lhashSet.add(new Integer("3"));
/* To copy all elements of java LinkedHashSet object into
array use Object[] toArray() method. */
Object[] objArray = lhashSet.toArray();
//display contents of Object array
System.out.println("LinkedHashSet elements are copied into an
Array. Now Array Contains..");
for(int index=0; index < objArray.length ; index++) {
System.out.println(objArray[index]);
}
}
}
TREESET
import java.util.Iterator;
import java.util.TreeSet;
public class TreeSetExample {
public static void main(String[] args) {
TreeSet<String> ts=new TreeSet<String>();
ts.add("b");
ts.add("a");
ts.add("d");
ts.add("c");
Iterator it=ts.iterator();
//Iterator it=ts.descendingIterator();
while(it.hasNext()) {
String value=(String)it.next();
System.out.println("Value :"+value);
}
}
}
LinkedList
public class LinkedList {
public interface Linkable {
public Linkable getNext();
public void setNext(Linkable node);
}
Linkable head;
public synchronized Linkable getHead() {
return head;
}

38
public synchronized void insertAtHead(Linkable node) {
node.setNext(head);
head = node;
}
public synchronized void insertAtTail(Linkable node) {
if (head == null) {
head = node;
} else {
Linkable p, q;
for (p = head; (q = p.getNext()) != null; p = q)
p.setNext(node);
}
}
public synchronized Linkable removeFromHead() {
Linkable node = head;
if (node != null) {
head = node.getNext();
node.setNext(null);
}
return node;
}
public synchronized Linkable removeFromTail() {
if (head == null) {
return null;
} Linkable p = head, q = null, next = head.getNext();
if (next == null) {
head = null;
return p;
}while ((next = p.getNext()) != null) {
q = p;
p = next;
} q.setNext(null);
return p;
} public synchronized void remove(Linkable node) {
if (head == null) {
return;
} if (node.equals(head)) {
head = head.getNext();
return;
} Linkable p = head, q = null;
while ((q = p.getNext()) != null) {
if (node.equals(q)) {
p.setNext(q.getNext());
return;
}
p = q;
}
}
static class LinkableInteger implements Linkable {
int i;
Linkable next;
public LinkableInteger(int i) {
this.i = i;
} public Linkable getNext() {

39
return next;
public void setNext(Linkable node) {
next = node;
}public String toString() {
return i + "";
} public boolean equals(Object o) {
return true;
}
if (!(o instanceof LinkableInteger))
return false;
if (((LinkableInteger) o).i == this.i) {
return true;
}
return false;
}

if (this == o){

}
}
public static void main(String[] args) {
LinkedList ll = new LinkedList(); // Create a list
ll.insertAtHead(new LinkableInteger(1));
ll.insertAtHead(new LinkableInteger(2));
ll.insertAtHead(new LinkableInteger(3));
ll.insertAtHead(new LinkableInteger(4));
ll.insertAtTail(new LinkableInteger(5));
ll.insertAtTail(new LinkableInteger(6));
System.out.println(ll.removeFromHead());
System.out.println(ll.removeFromTail());
ll.remove(new LinkableInteger(2));
for (Linkable l = ll.getHead(); l != null; l = l.getNext())
System.out.println(l);
}
}
java.util.ResourceBundle Subclasses
ListResourceBundle --> contain key/value pairs.
PropertyResourceBundle --> can be used to add properties file [as configuration file]
--> store in the form of text files
contain locale-specific objects
Resource bundles --> The keys uniquely identify a locale-specific object in the bundle.
--> Keys are always Strings
ResourceBundle myResources = ResourceBundle.getBundle("MyResources", currentLocale);
If you write own subclasses for resourceBundle it should override override two methods:
handleGetObject() and getKeys().
The java.util.ListResourceBundle is a subclass of java.util.ResourceBundle. It implements both
handleGetObjects and getKeys for you. The purpose of this bundle is to allow you to define localizable
elements as a two-dimensional array of <key, value> pairs. This bundle is easy to use and requires only
minimal code, which allows you to focus on providing data in the bundle instead.
A PropertyResourceBundle is definitely the easiest bundle to implement. It is nothing more than a text
file. A PropertyResourceBundle can have multiple lines, and each line is either a comment, blank line, or a
<key> = <value> entry. Property bundles should follow the same naming conventions as those used by
a ListResourceBundle. However, the differences are that property bundles are not compiled and that they
have a properties extension. So, the bundle below could be named

40

MyResource.properties.
ArrayResourceBundle is also there.
ResourceBundle Example with properties file
Resource1.properties
# This is the default LabelsBundle.properties file
s1 = computer
s2 = disk
s3 = monitor
s4 = keyboard
ResourceBundle labels =
ResourceBundle.getBundle("LabelsBundle", currentLocale);
Enumeration bundleKeys = labels.getKeys();
while (bundleKeys.hasMoreElements()) {
String key = (String)bundleKeys.nextElement();
String value = labels.getString(key);
System.out.println("key = " + key + ", " +
"value = " + value);
java.util.Enumeration interface
public interface Iterator
Iterator takes the place of Enumeration in the Java collections framework.
1. Iterators allow the caller to remove elements from the underlying collection during
the iteration with well-defined semantics.
2. Method names have been improved.
3. Provide traversal ,collection of objects.
4. Hasnext() next() remove()
The Iterator returned by List's iterator operation returns the elements of the list in proper sequence. List
also provides a richer iterator, called a ListIterator, which allows you to traverse the list in either
direction, modify the list during iteration, and obtain the current position of the iterator. The ListIterator
interface follows.
public interface ListIterator<E> extends Iterator<E> {
boolean hasNext();
E next();
boolean hasPrevious();
E previous();
int nextIndex();
int previousIndex();
void remove(); //optional
void set(E e); //optional
void add(E e); //optional
}
The three methods that ListIterator inherits from Iterator
(hasNext(), next(), and remove())
do exactly the same thing in both interfaces. The hasPrevious() and the previous()
operations are exact analogues of hasNext() and next().

41

The former operations refer to the element before the (implicit) cursor, whereas the latter refer to the
element after the cursor. The previous operation moves the cursor backward, whereas next moves it
forward.
Create jar file
jar cvf filename.jar * .class,* .gif etc.
Java.net package
URL URL myURL = new URL("http://example.com/");
URL myURL = new URL("http://example.com/pages/");
URL page1URL = new URL(myURL, "page1.html");
URL page2URL = new URL(myURL, "page2.html");
Constructor URL(URL baseURL, String relativeURL)
new URL("http", "example.com", "/pages/page1.html");
URL gamelan = new URL("http","example.com",80,"pages/page1.html");
Also use URI
URI uri = new URI("http", "example.com", "/hello world/", "");
URL url = uri.toURL(); // convert to URL
try {
URL myURL = new URL(. . .)
} catch (MalformedURLException e) {
...
// exception handler code here
...
}
Methods provided by URL
1.
2.
3.
4.
5.
6.
7.
8.

getProtocol Returns the protocol identifier component of the URL.


getAuthority Returns the authority component of the URL.
getHost Returns the host name component of the URL.
getPort Returns the port number component of the URL. The getPort method returns an integer
that is the port number. If the port is not set, getPort returns -1.
getPath Returns the path component of this URL.
getQuery Returns the query component of this URL.
getFile Returns the filename component of the URL. The getFile method returns the same as
getPath, plus the concatenation of the value of getQuery, if any.
getRef Returns the reference component of the URL.
URL class, along with these accessor methods, frees you from ever having to parse URLs again!
Given any string specification of a URL, just create a new URL object and call any of the accessor
methods for the information you need. This small example program creates a URL from a string
specification and then uses the URL object's accessor methods to parse the URL:
import java.net.*;
import java.io.*;
public class ParseURL {
public static void main(String[] args) throws Exception {

42

URL aURL = new URL("http://example.com:80/docs/books/tutorial"


+ "/index.html?name=networking#DOWNLOADING");
System.out.println("protocol = " + aURL.getProtocol());
System.out.println("authority = " + aURL.getAuthority());
System.out.println("host = " + aURL.getHost());
System.out.println("port = " + aURL.getPort());
System.out.println("path = " + aURL.getPath());
System.out.println("query = " + aURL.getQuery());
System.out.println("filename = " + aURL.getFile());
System.out.println("ref = " + aURL.getRef());

}
}
Here's the output displayed by the program:
protocol = http
authority = example.com:80
host = example.com
port = 80
path = /docs/books/tutorial/index.html
query = name=networking
filename = /docs/books/tutorial/index.html?name=networking
ref = DOWNLOADING
Read Directly from a URL
import java.net.*;
import java.io.*;
public class URLConnectionReader {
public static void main(String[] args) throws Exception {
URL oracle = new URL("http://www.oracle.com/");
URLConnection yc = oracle.openConnection();
BufferedReader in = new BufferedReader(
new InputStreamReader(
yc.getInputStream()));
String inputLine;

while ((inputLine = in.readLine()) != null)


System.out.println(inputLine);
in.close();

}
Connect to a URL use java.net.HttpURLConnection
try {
URL myURL = new URL("http://example.com/");
URLConnection myURLConnection = myURL.openConnection();
myURLConnection.connect();
} catch (MalformedURLException e) {
// new URL() failed
...
} catch (IOException e) {
// openConnection() failed
...

43
}
1.
2.
3.
4.
5.
6.
7.

Steps Involved
Create a URL.
Retrieve the URLConnection object.
Set output capability on the URLConnection.
Open a connection to the resource.
Get an output stream from the connection.
Write to the output stream.
Close the output stream.
A new URLConnection object is created every time by calling the openConnection method of the protocol
handler for this URL.
The output from this program is identical to the output from the program that opens a stream directly
from the URL.
Sockets - one end-point of a two-way communication link between two programs running on the
network. Socket classes are used to represent the connection between a client program and a server
program. The java.net package provides two classes--Socket and ServerSocket--that implement the client
side of the connection and the server side of the connection, respectively.
Sample
import java.io.*;
import java.net.*;
public class EchoClient {
public static void main(String[] args) throws IOException {
Socket echoSocket = null;
PrintWriter out = null;
BufferedReader in = null;
try {
echoSocket = new Socket("taranis", 7);
out = new PrintWriter(echoSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(
echoSocket.getInputStream()));
} catch (UnknownHostException e) {
System.err.println("Don't know about host: taranis.");
System.exit(1);
} catch (IOException e) {
System.err.println("Couldn't get I/O for "
+ "the connection to: taranis.");
System.exit(1);
}
BufferedReader stdIn = new BufferedReader(
new InputStreamReader(System.in));
String userInput;
while ((userInput = stdIn.readLine()) != null) {
out.println(userInput);
System.out.println("echo: " + in.readLine());
}

44

out.close();
in.close();
stdIn.close();
echoSocket.close();
}
}
Note that EchoClient both writes to and reads from its socket, thereby sending data to and receiving data
from the Echo server.
Server side 2 program 1. Protocol 2. ServerSocket
Socket clientSocket = null;
try {
clientSocket = serverSocket.accept();
} catch (IOException e) {
System.out.println("Accept failed: 4444");
System.exit(-1);
}
The accept method waits until a client starts up and requests a connection on the host and port of this
serverconnection is requested and successfully established, the accept method returns a new Socket
object which is bound to the same local port and has its remote address and remote port set to that of
the client. The server can communicate with the client over this new Socket and continue to listen for
client connection requests on the original ServerSocket
Datagram - datagram is an independent, self-contained message sent over the network whose
arrival, arrival time, and content are not guaranteed. Types
1. DatagramSocket
2. DatagramPacket,
3. MulticastSocket
socket = new DatagramSocket(4445);
InetAddress address = packet.getAddress();
int port = packet.getPort();
packet = new DatagramPacket(buf, buf.length, address, port);
socket.send(packet);
client side
byte[] buf = new byte[256];
InetAddress address = InetAddress.getByName(args[0]);
DatagramPacket packet = new DatagramPacket(buf, buf.length, address, 4445);
socket.send(packet);
MulticastSocket - used on the client-side to listen for packets that the server broadcasts to multiple
clients.
Types
1. MulticastServer,
2. MulticastServerThread,
3. MulticastClient.
DatagramSocket bound to port 4445 and opens the quote file. The DatagramSocket's port number
doesn't actually matter in this example because the client never send anything to the server.
The only method explicitly implemented in MulticastServerThread is its run method. The differences
between this run method and the one in QuoteServerThread are shown in bold:

45
Public void run {
try {
byte[] buf = new byte[256];
// don't wait for request...just send a quote
String dString = null;
if (in == null) {
dString = new Date().toString();
}
else {
dString = getNextQuote();
}
buf = dString.getBytes();
InetAddress group = InetAddress.getByName("203.0.113.0");
DatagramPacket packet;
packet = new DatagramPacket(buf, buf.length, group, 4446);
socket.send(packet);

NETWORK INTERFACE is the point of interconnection between a computer and a private or public

network. A network interface is generally a network interface card (NIC), but does not have to have a
physical form.
Socket soc = new java.net.Socket();
soc.connect(new InetSocketAddress(address, port));
NetworkInterface nif = NetworkInterface.getByName("bge0");
Enumeration<InetAddress> nifAddresses = nif.getInetAddresses();
Socket soc = new java.net.Socket();
soc.bind(nifAddresses.nextElement());
soc.connect(new InetSocketAddress(address, port));
NetworkInterface nif = NetworkInterface.getByName("bge0");
MulticastSocket() ms = new MulticastSocket();
ms.joinGroup(new InetSocketAddress(hostname, port) , nif);
The NetworkInterface class has no public constructor. Therefore, you cannot just create a new instance
of this class with the new operator. Instead, the following static methods are available so that you can
retrieve the interface details from the system: getByInetAddress(), getByName(), and
getNetworkInterfaces().
public class ListNIFs
{
public static void main(String args[]) throws SocketException {
Enumeration<NetworkInterface> nets = NetworkInterface.getNetworkInterfaces();

for (NetworkInterface netIf : Collections.list(nets)) {


out.printf("Display name: %s\n", netIf.getDisplayName());
out.printf("Name: %s\n", netIf.getName());
displaySubInterfaces(netIf);
out.printf("\n");
}

static void displaySubInterfaces(NetworkInterface netIf) throws SocketException {

46
Enumeration<NetworkInterface> subIfs = netIf.getSubInterfaces();
for (NetworkInterface subIf : Collections.list(subIfs)) {
out.printf("\tSub Interface Display name: %s\n", subIf.getDisplayName());
out.printf("\tSub Interface Name: %s\n", subIf.getName());
}
}

isLoopback() indicates if the network interface is a loopback interface.


isPointToPoint()
indicates if the interface is a point-to-point interface.
isVirtual() indicates if the interface is
a virtual interface.
Enumeration<NetworkInterface> nets = NetworkInterface.getNetworkInterfaces();
for (NetworkInterface netint : Collections.list(nets))
displayInterfaceInformation(netint);
static void displayInterfaceInformation(NetworkInterface netint) throws SocketException {
out.printf("Display name: %s\n", netint.getDisplayName());
out.printf("Name: %s\n", netint.getName());
Enumeration<InetAddress> inetAddresses = netint.getInetAddresses();
JDBC
JDBC Drivers are stored in Oracle-Odbc are linked along with through class path.
1. Sun JDBC-ODBC Driver (class 1 driver) Partial /Not Pure Thick Driver
uses jdbc odbx bridge
2. Native API Partially java driver
3. JDBC NET PURE JAVA Driver.

uses native code


Support 3 tier Architecture
is middleware / is partly java code

4. Native protocol pure java driver


4. Oracle thin Driver (Class 4 Driver)

support client server Architecture.


pure java driver
Best Performance.

While making use of a class 1 driver the connection with a database is established temporarily and after
execution of a particular query the connection established will be lost. In the case of class 4 driver the
connection is maintained (permanently) till the end. There will be no case that the connection may be
lost. Best Performance.
Class runtime value of a class / object.
Class.forName(Sun.jdbc.odbc.sunJdbcOdbcDriver);--> load the driver,
--> establish the connection
Class.forName(Sun.jdbc.odbc.sunJdbcOdbcDriver);
Connectioncon=driverManager.geConnection(URL);
Statement st;
String str = con.createStatement();
..
..

47

con.close()
for Class 4 Driver
Class.forName(Oracle.jdbc.driver.OracleDriver);
Connection con =DriverManager.getConnection(jdbc.Oracle.thin:@localHost:1521
Oracle9i,scott,tiger);
DriverManager only class in jdbc
getConnection( ) only method in that DriverManager Class.
More than 4096 characters in JDBC use getAsciiStream();
Example
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class Main {
public static void main(String[] args) throws Exception {
Connection conn = getConnection();
conn.setAutoCommit(false);
Statement st = conn.createStatement();
st.executeUpdate("create table survey (id int,name varchar(30));");
st.executeUpdate("insert into survey (id,name ) values (1,'nameValue')");
st = conn.createStatement();
ResultSet rs = st.executeQuery("SELECT * FROM survey");
rs.close();
st.close();
conn.close();
}
private static Connection getConnection() throws Exception {
String driver = "oracle.jdbc.driver.OracleDriver";
String url = "jdbc:oracle:thin:@localhost:1521:scorpian";
String username = "username";
String password = "password";
Class.forName(driver);
return DriverManager.getConnection(url, username, password);
}
}
DataSource object --> is used to establish connections
--> Increases application portability by making it possible for an application to use a
logical name for a datasource instead of having to supply information specific to a particular driver.
--> DataSource implementations must provide getter and setter
methods for each property. they support. These properties typically are initialized when the DataSource
object is deployed.
--> Although the Driver Manager can also be used to establish a connection,
connecting through a DataSource object is the preferred method.
configure a DataSource using a tool or manually
InitialContext ic = new InitialContext()

48
DataSource ds = ic.lookup("java:comp/env/jdbc/myDB");
Connection con = ds.getConnection();
DataSource ds = (DataSource) org.apache.derby.jdbc.ClientDataSource()
ds.setPort(1527);
ds.setHost("localhost");
ds.setUser("APP")
ds.setPassword("APP");
Connection con = ds.getConnection();
// Create Initial Context
DirContext ctx = new InitialDirContext(env);
// Get a copy of the same context
Context ctx2 = (Context)ctx.lookup("");
// Get a child context
Context ctx3 = (Context) ctx.lookup("ou=NewHires");
The above 3 context will share same connection.
With Initial Context with DSN Name
import java.sql.Connection;
import javax.naming.InitialContext;
import javax.sql.DataSource;
public class Main {
public static void main(String[] argv) throws Exception {
InitialContext init = new InitialContext();
DataSource source = (DataSource) init.lookup("dsn");
Connection connection = source.getConnection();
System.out.println("Connect to " + connection.getCatalog() + " a success!");
}
}
Establish an intialContext with JNDI interface
Like JDBC (Java Database Connectivity), JNDI is not a service, but a set of interfaces that allows
applications to access many different directory service providers using a standardized API. The deployed
enterprise beans in EJB have an environment-naming context that can be accessed using the JNDI API. It
also accesses an enterprise resource such as a data source or JavaMail session in a distributed computing
environment.
To do this, you must first obtain the initial context that contains the resource (a Java object).
The java.naming.Context interface provides methods for retrieving and updating this name-to-object
binding environment in which each name passed as an argument to a Context method is relative to that
context. A name parameter may never be null. Storing and retrieving objects from a JNDI namespace is
quite straightforward. You first obtain a JNDI naming context and then use the bind() and lookup()
methods to store and retrieve objects, as shown below:
Store and retrieve objects from a default JNDI namespace
import javax.naming.*;
public void createName() throws NamingException {
Context context = new InitialContext();
context.bind("java:comp/env", "MyApp");
}
public String getName() throws NamingException {
Context context = new InitialContext();
return (String) context.lookup("java:comp/env");
}

49

ResultSet interface --> provides methods for retrieving and manipulating the results of executed
queries, and ResultSet objects can have different functionality and characteristics. These characteristics
are result set type, result set concurrency, and cursor holdability.
--> ResultSet object is first created, the cursor is positioned before the first row.
--> A ResultSet object contains the results of a query.
--> A ResultSet is returned to an application when a SQL query is executed by a statement
object. The ResultSet object provides methods for iterating through the results of the
query.
--> ResultSet will be closed until con.close is used.
TYPE_FORWARD_ONLY ( The result set is not scrollable; its cursor moves forward only, from before
the first row to after the last row.
TYPE_SCROLL_INSENSITIVE The result set is scrollable; its cursor can move both forward and
backward relative to the current position, and it can move to an absolute position.
TYPE_SCROLL_SENSITIVE The result set is scrollable; its cursor can move both forward and
backward relative to the current position, and it can move to an absolute position Statement stmt =
con.createStatement
(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_READ_ONLY);
next() - moves the cursor forward one row. Returns true if the cursor is now positioned on a row and
false if the cursor is positioned after the last row.
previous() - moves the cursor backwards one row. Returns true if the cursor is now positioned on a row
and false if the cursor is positioned before the first row.
first() - moves the cursor to the first row in the ResultSet object. Returns true if the cursor is now
positioned on the first row and false if the ResultSet object does not contain any rows.
last() - moves the cursor to the last row in the ResultSet object. Returns true if the cursor is now
positioned on the last row and false if the ResultSet object does not contain any rows.
beforeFirst() - positions the cursor at the start of the ResultSet object, before the first row. If the
ResultSet object does not contain any rows, this method has no effect.
afterLast() - positions the cursor at the end of the ResultSet object, after the last row. If the ResultSet
object does not contain any rows, this method has no effect.
relative(int rows) - moves the cursor relative to its current position.
absolute(int row) - positions the cursor on the row-th row of the ResultSet object. A Connection object
controls the connection to the database. An application can alter the behavior of a connection by invoking
the methods associated with this object. An application uses the connection object to create statements.
statements Connection interface
Statement static
Prepared statement pre compiled
Callable statement dynamic

50
A PreparedStatement object is used when an application plans to reuse a statement multiple times.
The application prepares the SQL it plans to use. Once prepared, the application can specify values for
parameters in the prepared SQL statement.
The statement can be executed multiple times with different parameter values specified for each
execution.
A CallableStatement is used to call stored procedures that return values.The CallableStatement has
methods for retrieving the return values of the stored procedure.
Statement
Connectioncon=DriverManager.getConnection(URL,username,pwd);--> ref class 4 driver.
Statement st = con .createstatement();
Resultset rs
=stmt.executeQuery(select*fromtablename);
Prepared Statement
preparedStatementps=con.prepareStatement(updatetablenameSETM=?wherex=?);
--> m & x are fields in table tablename.
Callable statement --> for executing storedProcedure.
Connection con;
CallableStatement cs
=con.preparedCall({callSp_procedure_name};)Resultsetrs=cs.executeQuery();

With parameters [left output, right input] {? = call procedure_name[(?, ?, ...)]}


Execute the Query
boolean execute( ) Executes the SQL statement in this PreparedStatement object, which may be any
kind of SQL statement.
ResultSet executeQuery( ) Executes the SQL query in this PreparedStatement object and returns the
ResultSet object generated by the query.
int executeUpdate( ) Executes the SQL statement in this PreparedStatement object, which must be
an SQL INSERT, UPDATE or DELETE statement; or an SQL statement that returns nothing, such as a DDL
statement.
in JDBC we how we perform a simple transaction ?
Ans. we do with statement ,resultset
Disable autoCommit
Connection con.setAutoCommit(false);
Con.commit();
SavePoint
Write after a query is given while inserting multiple rows.
SavePointsp=con.setSavePoint(savepoint1);
..
con.rollback(sp);
con.releaseSavePoint(); --> Releases save point
Use addBatch() to execute set of records into the database at a time use execute Query.To access a
database from a web application, you must declare a resource reference in the application's web
application deployment. The resource reference specifies a JNDI name, the type of the data resource,

51
and the kind of authentication used when the resource is accessed. To specify a resource reference for a
Duke's Bookstore example using deploytool, follow these steps:
Select the WAR (jar cvf filename.war * .* (include javafiles,htmls,DD etc) ).
Select the Resource Ref's tab.
Click Add.
Type jdbc/BookDB in the Coded Name field.
Accept the default type javax.sql.DataSource.
Accept the default authorization Container.
Accept the default Sharable selected.
Reg Schema permission to a particular USER.
There are several statements related to schemas and users, and I will give a brief overview here to point
out the differences between the new commands added in SQL 2005, and the older system procedures
from previous versions.
To create a schema, you use not surprisingly CREATE SCHEMA, and most often you just say like:
CREATE SCHEMA myschema
CREATE SCHEMA is one of these statements that must be alone in batch. That is, no statements can
precede or follow it. That may seem a little funny for such a simple command, but there is an older form
of CREATE SCHEMA which is more complex that was introduced in SQL 6.5 and which serves a different
purpose. (Please see Books Online for details, if you really want to know.)
The preferred way to create a user since SQL 2005 is:
CREATE USER newuser [WITH DEFAULT_SCHEMA = someschema]
There are two system procedures to create users, sp_adduser and sp_grantdbaccess. They are both
deprecated and will be removed eventually. There is an important difference between CREATE USER and
the two system procedures: CREATE USER creates a user whose default schema is dbo, unless you
specify otherwise. On the other hand, sp_adduser and sp_grantdbaccess for compatibility reasons
perform the corresponding to:
CREATE SCHEMA newuser
go
CREATE USER newuser WITH DEFAULT_SCHEMA = newuser
go
ALTER AUTHORIZATION ON SCHEMA::newuser TO newuser
(The last command makes newuser owner of the schema created in his name.) Most likely, you don't
need that schema, so there is good reason to avoid these old system procedures entirely. CREATE USER
also has some options not offered by sp_adduser and sp_grantdbaccess. For instance, you can say:
CREATE USER thisdbonly WITHOUT LOGIN
This creates a database user that is not tied to a login. In some of the the test scripts, I use this option to
create test users, but you will also see examples where WITHOUT LOGIN can be used to create a user
that is a container for a certain permission. We will look at other options later in this article.
There is also CREATE ROLE that replaces sp_addrole in the same vein that CREATE USER replaces
sp_adduser. That is, CREATE ROLE creates the role only. sp_addrole also creates a schema that you
are unlikely to have any need for. And while we are at it, there is a CREATE LOGIN which replaces
sp_addlogin. As with CREATE USER, CREATE LOGIN has some new options, that we will come back to
later in this article.
Finally, there is DROP USER instead of sp_dropuser etc. A little note here: if you have users created
with sp_addlogin or sp_grantdbaccess, sp_dropuser is the most convenient way to drop them,
since there is a schema that needs to be dropped before you can drop the user, and DROP USER will not
do that for you.
Add Batch

52
import
import
import
import

java.sql.Connection;
java.sql.DriverManager;
java.sql.PreparedStatement;
java.sql.SQLException;

public class MainClass {


public static void main(String[] args) {
Connection connection = null;
PreparedStatement statement = null;
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
String url = "jdbc:mysql://localhost/database";
connection = DriverManager.getConnection(url, "username", "password");
String sql = "UPDATE employees SET email = ? WHERE employee_id = ?";
statement = connection.prepareStatement(sql);
statement.setString(1, "a@a.com");
statement.setLong(2, 1);
statement.addBatch();
statement.setString(1, "b@b.com");
statement.setLong(2, 2);
statement.addBatch();
statement.setString(1, "c@c.com");
statement.setLong(2, 3);
statement.addBatch();
statement.executeBatch();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (statement != null) {
try {
statement.close();
} catch (SQLException e) {
} // nothing we can do
}
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
} // nothing we can do
}
}
}
}
SetAsciiStream

53
import java.io.FileInputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.Statement;
public class Main {
public static void main(String[] args) throws Exception {
try {
String url = "jdbc:odbc:databaseName";
String driver = "sun.jdbc.odbc.JdbcOdbcDriver";
String user = "guest";
String password = "guest";
FileInputStream fis = new FileInputStream("somefile.txt");
Class.forName(driver);
Connection connection = DriverManager.getConnection(url, user, password);
Statement createTable = connection.createStatement();
createTable.executeUpdate("CREATE TABLE source_code (name CHAR(20), source
LONGTEXT)");
String ins = "INSERT INTO source_code VALUES(?,?)";
PreparedStatement statement = connection.prepareStatement(ins);
statement.setString(1, "TryInputStream"); // Set first field
statement.setAsciiStream(2, fis, fis.available()); // Stream is source
int rowsUpdated = statement.executeUpdate();
System.out.println("Rows affected: " + rowsUpdated);
connection.close();
} catch (Exception e) {
System.err.println(e);
}
}
}
// using a stored Procedure.
try {

int age = 39;


String poetName = "dylan thomas";
CallableStatement proc = connection.prepareCall("{ call set_death_age(?, ?) }");
proc.setString(1, poetName);
proc.setInt(2, age);
cs.execute();
}
catch (SQLException e)

// ....
}
//call a stored procedure with a parameter.
{? = call procedure_name[(?, ?, ...)]}
CallableStatement cstmt = con.prepareCall({callgetTestData(?,;)"})?
Output parameter.
CallableStatement cstmt = con.prepareCall(
"{call reviseTotal(?)}");

54
cstmt.setByte(1, (byte)25);
cstmt.registerOutParameter(1, java.sql.Types.TINYINT);
cstmt.executeUpdate();
byte x = cstmt.getByte(1);
cs.getInt(1)
(int I =5; I<=;i++) {
S.O.P(cs.getString(i) );
Return cs.getInt(1); }
Use getMoreResults() to create multiple resultsets with same name.

for

Using Transactions with JDBC


Transaction management with JDBC takes place via the Connectionobject. By default, new connections
start out in auto-commit mode. This means that every SQL statement is executed as an individual
transaction that is immediately committed to the database
import
import
import
import

java.io.*;
java.sql.*;
javax.servlet.*;
javax.servlet.http.*;

public class OrderHandler extends HttpServlet {


public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException,
IOException {
res.setContentType("text/plain");
PrintWriter out = res.getWriter();
Connection con = null;
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con = DriverManager.getConnection("jdbc:odbc:ordersdb", "user", "passwd");
// Turn on transactions
con.setAutoCommit(false);
Statement stmt = con.createStatement();
stmt.executeUpdate( "UPDATE INVENTORY SET STOCK = (STOCK - 10)
WHERE PRODUCTID = 7");
stmt.executeUpdate( "UPDATE SHIPPING SET SHIPPED = (SHIPPED +
WHERE PRODUCTID = 7");
chargeCard(); // method doesn't actually exist...
con.commit();
out.println("Order successful! Thanks for your business!");
}
catch (Exception e) {
// Any error is grounds for rollback
try {
con.rollback();
}
catch (SQLException ignored) { }
out.println("Order failed. Please contact technical support.");
}
finally {
// Clean up.

55

} } }

try {
if (con != null) con.close();
}
catch (SQLException ignored) { }

This section looks at a very simple stored procedure that has no parameters. Even though most stored
procedures do something more complex than this example, it serves to illustrate some basic points about
them. As previously stated, the syntax for defining a stored procedure is different for each DBMS. For
example, some use begin . . . end or other keywords to indicate the beginning and ending of the
procedure definition. In some DBMSs, the following SQL statement creates a stored procedure:
create procedure SHOW_SUPPLIERS
as
select SUPPLIERS.SUP_NAME, COFFEES.COF_NAME
from SUPPLIERS, COFFEES
where SUPPLIERS.SUP_ID = COFFEES.SUP_ID
order by SUP_NAME
The following code puts the SQL statement into a string and assigns it to the variable createProcedure ,
which we will use later:
String createProcedure = "create procedure SHOW_SUPPLIERS " +
"as " +
"select SUPPLIERS.SUP_NAME, COFFEES.COF_NAME " +
"from SUPPLIERS, COFFEES " +
"where SUPPLIERS.SUP_ID = COFFEES.SUP_ID " +
"order by SUP_NAME";
The following code fragment uses the Connection object con to create a Statement object, which is used
to send the SQL statement creating the stored procedure to the database:
Statement stmt = con.createStatement();
stmt.executeUpdate(createProcedure);
The procedure SHOW_SUPPLIERS will be compiled and stored in the database as a database object that
can be called, similar to the way you would call a method.
Calling a Stored Procedure from JDBC
JDBC allows you to call a database stored procedure from an application written in the Java programming
language. The first step is to create a CallableStatement object. As with Statement and
PreparedStatement objects, this is done with an open Connection object. A CallableStatement object
contains a call to a stored procedure; it does not contain the stored procedure itself. The first line of code
below creates a call to the stored procedure SHOW_SUPPLIERS using the connection con . The part that
is enclosed in curly braces is the escape syntax for stored procedures. When the driver encounters "{call
SHOW_SUPPLIERS}" , it will translate this escape syntax into the native SQL used by the database to call
the stored procedure named SHOW_SUPPLIERS .
CallableStatement cs = con.prepareCall("{call SHOW_SUPPLIERS}");
ResultSet rs = cs.executeQuery();
The ResultSet rs will be similar to the following:
SUP_NAME
COF_NAME
-------------------------------------Acme, Inc.
Colombian
Acme, Inc.
Colombian_Decaf
Superior Coffee
French_Roast
Superior Coffee
French_Roast_Decaf
The High Ground
Espresso

56
Note that the method used to execute cs is executeQuery because cs calls a stored procedure that
contains one query and thus produces one result set. If the procedure had contained one update or one
DDL statement, the method executeUpdate would have been the one to use. It is sometimes the case,
however, that a stored procedure contains more than one SQL statement, in which case it will produce
more than one result set, more than one update count, or some combination of result sets and update
counts. In this case, where there are multiple results, the method execute should be used to execute the
CallableStatement .
The class CallableStatement is a subclass of PreparedStatement , so a CallableStatement object can take
input parameters just as a PreparedStatement object can. In addition, a CallableStatement object can
take output parameters or parameters that are for both input and output. INOUT parameters and the
method execute are used rarely. For complete information, refer to JDBC Database Access with Java.
To create the connection to the database, the data access object
database.BookDBAO looks up the JNDI name of the bookstore data source object:
public BookDBAO () throws Exception {
try {
Context initCtx = new InitialContext();
Context envCtx = (Context)
initCtx.lookup("java:comp/env");
DataSource ds = (DataSource) envCtx.lookup("jdbc/BookDB");
con = ds.getConnection();
System.out.println("Created connection to database.");
}
catch (Exception ex) {
System.out.println("Couldn't create connection." +
ex.getMessage());
throw new Exception("Couldn't open connection to database: " + ex.getMessage());
}
Mapping the Resource Reference to a Data Source.
Both the web application resource reference and the data source defined in the Application Server have
JNDI names. See JNDI Naming for a discussion of the benefits of using JNDI naming for resources.
To connect the resource reference to the data source, you must map the JNDI name of the former to the
latter. This mapping is stored in the web application runtime deployment descriptor.
To create this mapping using deploytool, follow these steps:
1.
2.
3.
4.
5.
6.

Select localhost:4848 in the Servers list to retrieve the data


sources defined in the Application Server.
Select the WAR in the Web WARs list.
Select the Resource Ref's tab.
Select the Resource Reference Name, jdbc/BookDB, defined in the previous section.
In the Sun-specific Settings frame, select jdbc/BookDB from the JNDI Name drop-down list.

For Retrieval of value from a DATABASE


Class.forName(oracle.jdbc.driver.OracleDriver);
Connectioncon=driverManager.getConnection(jdbc.oracle.thin:@localhost:1521,Oracle91,scott,
tiger);
Statement st;

57
String st= con.createStatement();
Resultset rs ;
Rs.executeQuery();
While(rs.next()) {
stringBuffer sb=rs.value();
}
String str = sb.toString();
}
For Retrieval of value from a DATABASE
Class.forName(oracle.jdbc.driver.OracleDriver);
Connectioncon=driverManager.getConnection(jdbc.oracle.thin:@localhost:1521,Oracle91,scott,
tiger);
Statement st;
String st= con.createStatement();
Resultset rs ;
Rs.executeQuery();
While(rs.next()){
stringBuffer sb=rs.value();
}
String str = sb.toString(); }
what is the advantage of datasource over drivermanager? I think its manageable
connections ?
datasource is lookup configurable ,DM is hardcode , use JNDi to look up, JNDI InitialContextFactory
DB JAR FILES USED FOR JDBC
FOR ORACLE : CLASSES13.JAR
FOR MYSQL : mysql308.jar
FOR DB2 : DB2GCC.jar
what is JNDI, can you explain me a few words in it ?
To access an enterprise resource such as a data source or JavaMail session in a distributed
computing environment, you can use the JNDI API to locate that object so that you can use it in your
code. To do this, you must first obtain the initial context that contains the resource (a Java object).

This can be done in 2 ways.


1. Get an initial context using JNDI properties found in the current environment
The current environment includes the Java system properties and properties defined in properties files
found in the classpath. This code snippet illustrates how to obtain the initial context from these
properties:
import javax.naming.Context;
import javax.naming.InitialContext;
// ... class declaration, method declaration code here ...
Context initialContext = new InitialContext();
Get an initial context by explicitly setting JNDI properties
JNDI clients should assume that the correct environment is already configured. If this is the case, there is

58
no need for you to explicitly set property values and pass them to the constructor of the InitialContext
object. However, a JNDI client might need to access a namespace other than the one identified in its
environment. In this event, you must explicitly set one or more properties used by the InitialContext
constructor. Any property values you pass to the InitialContext constructor take precedence over settings
of the equivalent properties found elsewhere in the client's environment.
This code snippet illustrates this technique:
import java.util.Hashtable;
import javax.naming.Context;
import javax.naming.InitialContext;
// ... class declaration, method declaration code here ...
Hashtable env = new Hashtable();
env.put(Context.INITIAL_CONTEXT_FACTORY, "com.ibm.websphere.naming.
WsnInitialContextFactory");
env.put(Context.PROVIDER_URL, "iiop://myhost.mycompany.com:2809");
Context initialContext = new InitialContext(env);
what is SQL Exception?
An exception that gives all kind of errors happend at the time of insert or retrieve data from DB.
it has few methods like geterrorcode()
what is a cachedrowset in JDBC ?
CachedRowset is used to maintain data after terminating the connection.
CachedRowSetImpl crs = new CachedRowSetImpl();
crs.populate(resultSet);
to transfer query results between classes
EXAMPLE
<%@ page import="sun.jdbc.rowset.CachedRowSet" %>
<HTML>
<HEAD>
<jsp:useBean id="Contacts" class="sun.jdbc.rowset.CachedRowSet" scope="session">
<% Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); // initialize our CachedRowSet bean
Contacts.setUsername("user");
Contacts.setPassword("password");
Contacts.setUrl("jdbc:odbc:mydsn");
// some drivers require this
Contacts.setTableName("Contacts");
Contacts.setCommand("SELECT name, telephone from Contacts");
Contacts.execute();
Contacts.first();
%>
</jsp:useBean>
<%
// get the servlet request object
javax.servlet.ServletRequest req = pageContext.getRequest();
// process updates
boolean updateRow = false;
String contactName = Contacts.getString(1);
String newValue = req.getParameter("ContactName");
if (( newValue != null) && (!newValue.equals( contactName ))) {

59
Contacts.updateString( 1,req.getParameter("ContactName"));
updateRow = true;

}
String contactPhone = Contacts.getString(2);
newValue = req.getParameter("ContactPhone");
if (( newValue != null) && (!newValue.equals(contactPhone))) {
Contacts.updateString( 2, req.getParameter("ContactPhone"));
updateRow = true;
}
if (updateRow) Contacts.updateRow();
// process navigation commands
if ( req.getParameter("next") != null ) {
if (! Contacts.next() ) Contacts.last();
} else if ( req.getParameter("prev") != null) {
if (! Contacts.previous()) Contacts.first();
} else if ( req.getParameter("save") != null) {
Contacts.acceptChanges();
} else if ( req.getParameter("insert") != null) {
Contacts.moveToInsertRow();
Contacts.updateString(1, "");
Contacts.updateString(2, "");
Contacts.insertRow();
Contacts.moveToCurrentRow();
Contacts.next();
} else if ( req.getParameter("delete") != null) {
Contacts.deleteRow();
if (!Contacts.next()) Contacts.last(); %>
<STYLE>
BODY { font-style: verdana }
</STYLE>
<TITLE>
CachedRowSetExample
</TITLE>
</HEAD>
<BODY BGCOLOR='lightgrey'>
<H2>Contacts</H2>
<FORM>
<TABLE BORDER='0'>
<TR><TD>Name:</TD><TD>Telephone number:</TD></TR>
<TR>
<TD><INPUT TYPE='text' NAME="ContactName"VALUE='<%=Contacts.getString(1)%>'/> </TD>
<TD><INPUT TYPE="text"NAME="ContactPhone"VALUE='<%=Contacts.getString(2)%>'/> </TD>
</TABLE>
<INPUT TYPE="submit" NAME="prev" VALUE=" < "/>
<INPUT TYPE="submit" NAME="next" VALUE=" > "/>
<INPUT TYPE="submit" NAME="insert" VALUE="Insert"/>
<INPUT TYPE="submit" NAME="delete" VALUE="Delete"/>
<INPUT TYPE="submit" NAME="save" VALUE="Save"/>
Record <%=Contacts.getRow()%> of <%=Contacts.size()%>
</FORM>
</BODY>
</HTML>

60

How you set the length of a resultset or what is the max length for resultset ?
u cant set
In JDBC when I close a connection , is there a need to close resultset etc ?
is it needed or not ?

if the result set is not going to be required further its advisable to be closed
it occopy resources free them resources are costly optimum usage is required. Most Java programmers
close a connection with database directly without closing the ResultSet. This is okay with standalone Java
programs, where the Java compiler automatically closes the Resultset for you, but when we deploy this
code in a servlet, then we are not guaranteed this behavior.
Connection Pooling
The ConnectionPool class maintains a Hashtable, using Connection objects as keys and Boolean
objects as stored values. The Boolean value indicates whether a connection is in use. A program calls the
getConnection() method of ConnectionPool to be assigned a Connection object it can use; it calls
returnConnection() to give the connection back to the pool. This is a fairly simple model of a connection
pool. For deployment, you probably want something that does a better job of maintaining the quality of
the pool and does more verification of integrity than a simple call to setAutoCommit() .
Using the DataSource interface (JDBC 2.0) or the DriverManager (JDBC 1.0) interface, a J2EE component
could get physical database connection objects.
Handle OutOfMemoryError In Java
java Xmx 512M in console.
when you want to handle an OOME, make sure you do absolutely *no* object allocations within the catch
block. If you need certain objects (like a dialog to display a message to the user) then these MUST be
allocated *before* the OOME ever occurred.
Don't bother trying to trigger a garbage collection cycle -- you can be sure the VM has already made its
very best effort to free up enough memory. If there are variables that you can set to null in order to free
some memory, then consider replacing those strong references with SoftReferences instead.
JMP is a profiler for java that can be used to trace objects usage and method timings.
Servlets
Web Container
1.communication support --> between servlets & web servers
2.Life Cycle Management --> life and death of servlets & JSP
3.Multithreading support --> create and save threads to each servlets.
4.Declarative security
--> http://localhost:8080/index.html
5.JSPSupport
--> JSP into Servlets.
Servlet It is a server side component used to Transfer information to a user which is
embedded in a HTTP Servlets.
Servlets are modules that extend request/response-oriented servers, such as javaenabled web servers.For example, a servlet might be responsible for taking data in an HTML order-entry
formandapplyingthebusinesslogicusedtoupdateacompanysorderdatabase.

61

ServletContext Defines a set of methods that a servlet uses to communicate with its servlet
container,
refer to all / Common applications total web application. even to a jar file.
public interface ServletContext
for example, to get the MIME type of a file, dispatch requests, or write to a log file.
There is one context per "web application" per Java Virtual Machine. (A "web application" is a
collection of servlets and content installed under a specific subset of the server's URL namespace such as
/catalog and possibly installed via a .war file.)
In the case of a web application marked "distributed" in its deployment descriptor, there will be
one context instance for each virtual machine, the context cannot be used as a location to share global
information (because the information won't be truly global). Use an external resource like a database
instead.
servletContext.getParameter(name,Value);
servletConetxt.setParameter(name,Value);
ServletContext context = getServletContext();
InputStream is = context.getResourceAsStream("/yourfilename.cnf");
The ServletContext.getResourceAsStream() method the file can be located anywhere in your web
application. It is recommended to keep it under the /WEB-INF directory if you don't want browers
being able to access it. Your web application should use the ServletContext.getResourceAsStream()
API when accessing web application resources. ServletContext Defines a set of methods that a servlet
uses to communicate with its servlet container.
The ServletContext object is contained within the ServletConfig object, which the Web server
provides the servlet when the servlet is initialized.
You can specify param-value pairs for ServletContext object in <context-param> tags in web.xml file.
The ServletConfig parameters are specified for a particular servlet and are unknown to other
servlets. The ServletContext parameters are specified for an entire application outside of any particular
servlet and are available to all the servlets within that application.
public interface ServletConfig
ServletConfig is a servlet configuration object used by a servlet container used to pass
information to a servlet during initialization. All of its initialization parameters can ONLY be set in
deployment descriptor.
This interface is implemented by services in order to pass configuration information to a servlet
when it is first loaded. A service writer implementing this interface must write methods for the servlet to
use to get its initialization parameters and the context in which it is running.
A servlet configuration object used by a servlet container to pass information to a servlet during
initialization refer to particular (servlet) applications.to set() and get() value from a object.
getInitParameter(String) Returns a string containing the value of the named initialization
parameter of the servlet, or null if the parameter does not exist.
getInitParameterNames() Returns the names of the servlet's initialization parameters as an
enumeration of strings, or an empty enumeration if there are no initialization parameters.
getServletContext()

Returns the context for the servlet.

servletConfig.getParameter(name,Value);
servletConfig.setParameter(name,Value);

62
ServletConfig config = context.getServletConfig
Config.getInitparameters ();
Generic Servlet
Support all kind of protocols like
FTP,TCP,IP,UDP including HTTP.
Application server support all kind of protocols.
Weblogic,WebSphere,JBoss all can be
used.

()
HTTP-Servlet
Support only HTTP Protocol.
WebServer support only HTTP Protocol.
Weblogic,WebSphere,JBoss all can be
used also TomCat.

1.Generic( super class of all servlets)


Methods
1. public void destroy()
2. public java.lang.String getInitParameter(java.lang.String name)
3. public java.util.Enumeration getInitParameterNames()
4. public ServletConfig getServletConfig()
5. public ServletContext getServletContext()
6. public java.lang.String getServletInfo()
7. public void init(ServletConfig config)throws ServletException
8. public abstract void service(ServletRequest req, ServletResponse res)throws
ServletException,IOException
9. public java.lang.String getServletName()
HttpServlet
Servlet Life Cycle
Init( ) & destroy( ) will be called only once. Service( ) will be called when first request is
generated called any number of times .
Init( ) --> Public void init(servletConfig sc) throws ServletException,IOException
Service( )
Public void service(HttpServletRequest req, HttpServletResponse res) throws
IOException, ServletException
Public void doGet(HttpServletRequest req, HttpServletResponse res) throws
IOException, ServletException --> get resource file
Public void doPost(HttpServletRequest req, HttpServletResponse res) throws
IOException, ServletException --> doget() with extra info
Public void doOptions(HttpServletRequest req, HttpServletResponse res) throws
IOException, ServletException --> list of HTTP Methods
Public void doTrace(HttpServletRequest req, HttpServletResponse res) throws
IOException, ServletException --> client can see what is sent in other end.
Public void doPut(httpServletRequest req, HttpServletResponse res) throws
IOException, ServletException --> put into request URL
Public void doDelete(httpServletRequest req, HttpServletResponse res) throws
IOException, ServletException --> delete info from Requested URL
Public void getServletInfo(httpServletRequest req, HttpServletResponse res) throws
IOException, ServletException
Destroy( )
Public void destroy() throws IOException, ServletException
constructor
constructors for dynamically loaded Java

Servlets init()
typically used to perform servlet initialization

63
classes (such as servlets) couldn't accept
arguments.

creating or loading objects that are used by the


servlet in the handling of its requests .
to provide a new servlet any information about itself
and its environment, a server had to call a servlet's
init() method and pass along an object that
implements the ServletConfig interface
ServletEngine / JSPEngine container calls web.xml
COMMUNI CATION WITH HTML
<inputtype=submitname=submitvalue=submitaction=urlpage/ *.do>
Data Transfer between Servlets
1. getParameter()
2.setParameter()
3. getInitPrameter()
package jsp.tutorials.servletexample;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class WelcomeServlet extends HttpServlet {

@Override

public void init(ServletConfig config) throws ServletException {


super.init(config);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
/* * Get the value of form parameter */
String name = request.getParameter("name");
String welcomeMessage = "Welcome "+name;
/* Set the content type(MIME Type) of the response. */
response.setContentType("text/html");
PrintWriter out = response.getWriter();
/* * Write the HTML to the response */
out.println("<html>");
out.println("<head>");
out.println("<title> A very simple servlet example</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>"+welcomeMessage+"</h1>");
out.println("<a href="/servletexample/pages/form.html">"+"Click here to go back to input page
"+"</a>");
out.println("</body>");
out.println("</html>");
out.close();
}
public void destroy() {
}
}

64

Port Numbers
Oracle 1521 ,WebLogic 7001 , RMI 1099, Tomcat 8080.
doGet( )
allow only 256 characters at a time.
URL will be displayed.not secure.
To avoid URL Display use encodeURL()
togetthings.CantmodifyanythingfromServer.
Servlet Context
ServletContext Defines a set of methods that a
servlet uses to communicate with its servlet
container.
The ServletContext object is contained within the
ServletConfig object, which the Web server provides
the servlet when the servlet is initialized.
You can specify param-value pairs for
ServletContext object in <context-param> tags in
web.xml file.
The ServletContext parameters are specified for an
entire application outside of any particular servlet
and are available to all the servlets within that
application

doPost( )
allow any number of characters at
a time.
url will not be displayed.
to send data to be processed.
Servlet Config.
The ServletConfig parameters are
specified for a particular servlet and are
unknown to other servlets

Deployment Descriptor web.XML contents.


<web-app>
<servlet>
<servlet name> . . . . </servlet-name>
< servlet-class> . . . . </servlet-class>
</servlet>
<servelt-Mapping>
<servelt-name> . . . .</servelt-name>
<url-pattern> . . . . . </url-pattern>
</servlet-Mapping>
<load-on-startup>1</load-on-startup> --> alternate way to create instance.
<session-config>
<session-timeout> 50 </session-timeout> --> can invalidate of session if put 0.
</session-config>
<error-page>
<error-code> 404</error-code>
<exception-type>Exception</exception-type>
<location>/ filename.jsp</location>
</error-page>
<jsp-config>
<taglib>
<taglib-uri>---</taglib-uri>
<taglib-location>--</taglib-location>
</taglib>
</jsp-config>
</web-app>
HttpServletRequest , HttpServeltResponse --> Interfaces.

65

Javax.servlet contains:
Interfaces
Servlet
ServletRequest
ServletResponse
ServletConfig
ServletContext
SingleThreadModel

Classes
Generic Servlet
ServletInputStream
ServletOutputStream
ServletException
UnavailableException

Javax.servlet.http contains:
Interfaces
HttpServletRequest
HttpServletResponse
HttpSession
HttpSessionContext
HttpSessionBindingListener

Classes
Cookie
HttpServlet
HttpSessionBindingEvent
HttpUtils

A Sample File Upload Program using Servlets


import java.io.IOException;
import java.io.File;
import java.io.PrintStream;
import java.io.ByteArrayOutputStream;
import java.util.Hashtable;
import java.util.Enumeration;
import javax.servlet.* ;
import javax.servlet.http.* ;
/* *
* This is a basic file upload servlet. It will handle file uploads,
* as performed by Netscape 3 and 4. Note: This program does not
implement RFC 1867, merely a subset of it.
*/
public class FileUploadServlet extends HttpServlet {
protected int maxSize = // ...
public void init( ServletConfig sc )
{ // ... }
/* * * Since fileupload requires POST, we only override this method. * /
protected void doPost( HttpServletRequest req, HttpServletResponse res )
throws ServletException, IOException
{ // ... }
/* * * Obtain information on this servlet.
* @return String describing this servlet.
*/
public String getServletInfo()
{
return "File upload servlet -- used to receive files";
}
when i login to 1 application the path should forward to all the applications with out relogin
SSO is one of them
2.store uid and pwd in session

66
3.store uid and pwd in DB
Predefined Objects.
1. request
2.response
3.servletRequest
4.servletResponse
5.Session
6.Exception
7.Cookie.
printWriter out = res.getWriter();
out.println() ;--> write data in Character Stream.
ServeltOutputStream out1= res.getOutputStream()
Out.write(oByteArray); --> Write in byte Stream.
To restrict a servlet/ JSP to display in browser
Res.setHeader(pragma, no cache);
bufferSize = 0 kb; // in JSP
Servlet chaining is a technique in which two or more servlets can cooperate in servicing a single
request.Inservletchaining,oneservletsoutputispipedtothenextservletsinput.Thisprocess
continues until the last servlet is reached. Its output is then sent back to the client.
Servlet Tunneling : Used in applet to servlet communications, a layer over http is built so as to enable
object serialization.
Context
GetAttribute()
SetAttribute()
RemoveAttribute()
GetAttributeNames()

ServletRequest
GetAttribute()
SetAttribute()
RemoveAttribute()
GetAttributeNames()

HttpSession
GetAttribute()
SetAttribute()
RemoveAttribute()
GetAttributeNames()

For storing a variable temporarily for a particular request -->Req.setAttribute(name,value);


For storing a variable temporarily for a particular request -->session.SetAttribute(name,value);
GetServeltContext().setAttribute(name,value);
GetServeltContext().getAttribute(name);--> will print its value.
Lock Session & Context --> synchronized(getServletContext());
synchronized(session);
Session Tracking Methods.
1. Cookie( ) it is a piece of information generated on the client side for identification of server.
Cookie c1 = new Cookie();
c1.setValue(name,value);
c1.getCookie();
c1.setMaxAge(0) --> delete cookie
2.Hidden fields and Query strings transfer data from page 1 to page 2 as hidden fields.
3.URL Rewriting.

67
Response.encodeURL(/el.do)
Response.encodeRedirectURL(/el.do) add extra session id to this URL
4. Session( )
It is the time difference between a user login and logout. Store on the server side.
HttpSession --> interface.
HttpSession. S1=req.getSession(false); --> continue with existing session ID.
HttpSession. S1=req.getSession(true); --> create new session.
HttpSession.getSession(true);
S1.setSession(name,value);
S1.getSession();
session.isNew() --> check if session is available.
Major methods in Session
getCreationTime();
getLastAccessedTime();
getMaxInactiveInterval();
setMaxInactiveInterval();
invalidate();
Close Session techniques
1. timeout.
2. close application
3. session.invalidate()
4. setMaxInactiveInterval(0) --> close session immediately.
5.Authentication --> Using HTTPS protocol.
HTTPS Protocol define in Web.xml
<securityconstraint>
<userdataconstraint>
<transport-guarentee>
CONFIDENTIAL
<transport-Guarentee>
</userData-Constraint>
<security-constraint>
as on webService.xml

Inprotocol=HTTPS

Hidden field.
The disadvantage is that every user action must result in the submission of a form or you lose
the data. This limits the sort of HTML you can put on the page.
Since hidden fields put all previous data on each form as you go through several forms the pages
transmitted get bigger, and bigger, and bigger -- taking longer, and longer, and longer to load.
Read XML DATA
String XML=xml_data_as_a_string;
File f = new File(C:\xmlData);
FileWriter fw= new FileWriter(f);
Fw.write(xml);
singleThreadModel
execute one servlet ( Thread) at a time.

68
class c1 extends httpServletRequest implements singleThreadModel . when a class get more than 1
request ,more than 1 instance will be created for a particular class.
SSI Server Side Include :
Server-Side Includes allows embedding servlets within HTML pages using a special servlet tag.
In many servlets that support servlets, a page can be processed by the server to include output from
servlets at certain points inside the HTML page. This is accomplished using a special internal SSINCLUDE,
which processes the servlet tags. SSINCLUDE servlet will be invoked whenever a file with an. shtml
extension is requested. So HTML files that include server-side includes must be stored with an .shtml
extension.
servlet servlet communication
servletcontext.config.getServlet(reqURL)
TestServlet test= (TestServlet)getServletConfig().getServletContext().getServlet("OtherServlet");
Servlet Servlet / JSP communication
1.servletcontext.config.requestDespacher(reqURL)
include(req,res); forward(req,res);
RequestDispatcher
request.setAttribute("selectedScreen", request.getServletPath());
1. RequestDispatcher dispatcher = request.getRequestDispatcher ("/template.jsp");
if (dispatcher != null) { dispatcher.forward(request, response); }
2. servletcontext.config.sendRedirect(reqURL)
SendRedirect
String destination ="/jsp/destination.jsp";
response.sendRedirect(response.encodeRedirectURL(destination));
response.sendRedirect(response.encodeRedirectURL("http://www.google.com"));
Read a Data from XML
ServletContext context = getServletContext();
String myValue = context.getInitParameter("emailid");
Forward( ) : javax.Servlet.RequestDispatcher interface.
- RequestDispatcher.forward( ) works on the Server.
- The forward( ) works inside the WebContainer.
- The forward( ) restricts you to redirect only to a resource in the same web-Application.
- After executing the forward( ), the control will return back to the same method from where the forward
method was called.
- The forward( ) will redirect in the application server itself, it does'n come back to the client.
- The forward( ) is faster than Sendredirect( ) .
To use the forward( ) of the requestDispatcher interface, the first thing to do is to obtain
RequestDispatcher Object. The Servlet technology provides in three ways.
1. By using the getRequestDispatcher( ) of the javax.Servlet.ServletContext interface , passing a String
containing the path of the other resources, path is relative to the root of the ServletContext.
RequestDispatcher rd=request.getRequestDispatcher ("secondServlet");
Rd.forward(request, response);

69

2. getRequestDispatcher( ) of the javax.Servlet.Request interface , the path is relative to current


HtpRequest.
RequestDispatcher rd=getServletContext( ).getRequestDispatcher("servlet/secondServlet");
Rd.forward(request, response);
3. By using the getNameDispatcher( ) of the javax.Servlet.ServletContext interface.
RequestDispatcher rd=getServletContext( ).getNameDispatcher("secondServlet");
Rd.forward(request, response);
Sendredirect( ) : javax.Servlet.Http.HttpServletResponce interface
- RequestDispatcher.SendRedirect( ) works on the browser.
- The SendRedirect( ) allows you to redirect trip to the Client.
- The SendRedirect( ) allows you to redirect to any URL.
- After executing the SendRedirect( ) the control will not return back to same method.
- The Client receives the Http response code 302 indicating that temporarly the client is being redirected
to the specified location , if the specified location is relative , this method converts it into an absolute URL
before redirecting.
- The SendRedirect( ) will come to the Client and go back,.. ie URL appending will happen.
Response. SendRedirect( "absolute path");
Absolutepath other than application , relative path - same application.
When you invoke a forward request, the request is sent to another resource on the server, without the
client being informed that a different resource is going to process the request. This process occurs
completely with in the web container. When a sendRedirtect method is invoked, it causes the web
container to return to the browser indicating that a new URL should be requested. Because the browser
issues a completely new request any object that are stored as request attributes before the redirect
occurs will be lost. This extra round trip a redirect is slower than forward.
Include
method this is used to tag in the contents of a
resource as a part of the response flow as if it
were part of the calling servlet. If you include a
jsp or a servlet, it must not attempt to change
the response status code or the http headers, as
any such request will be ignored.

Forward
this method is used to show a different resource
in place of the servlet originally requested. This
resource may be a jsp, a servlet etc. When a
request is sent from the client to the web server
through an url , the web container intercepts the
request and sends it to another resource without
the knowledge of the client browser. And a
response is received from that resource after
processing of the request is done.

RequestDespatcher
control between servlets will be forwarded
temporarily from one to another and is
received back in servlet communications.

sendRedirect
control is forward permanently from
one servlet to another on servlet
communications

Include
Connection is temporarily forwarded and
returned back
SendRedirect
1. always sends a header back to the
client/browser. this header then contains the
resource(page/servlet) which u wanted to be

Forward
Control is permanently forwarded to next servlet.
Forward
1. resources from the server, where the fwd. call
was made, can only be requested for.

70
redirected.
2. the browser uses this header to make another
fresh request.
3. sendRedirect has a overhead as to the extra
remort trip being incurred.

2.forward just routes the request to the new


resources which u specify in ur forward call.
3.That means this route is made by the servlet
engine at the server level only.
no headers r sent to the browser which makes
this very eficient.
4. the advantage is that u can point to any
4.also the request and response objects remain
resource
the same both from where the forward call was
made and the resource which was called.
res.sendRedirect ()
Jsp:Forward( )
With response.sendRedirect(), the browser is
<jsp:forward> is more efficient. It forwards the
asked to go get another page. All HTTP
request to the specified JSP page on the server
parameters of the original request are lost. The
side, without asking the browser to generate a
browser's location bar changes.
new request. You can only forward to resources
served by your application server! It also keeps
the state. The browser's location bar doesn't
change.
Filters --> Afilterisanobjectthatcantransformarequestormodifyaresponse.Itwont
create response . They are preprocessors of requests before they reach a Servlet and
postprocessors of responses after leaving a Servlet.
Implement javax.servlet.filter I nterface
Servlet filters can:
Intercept a Servlet's invocation before the Servlet is called.
Examine a request before the destination Servlet is invoked.
Modify request headers and request data by subclassing the HttpServletRequest
object and wrapping the original request.
Modify the response headers and response data by subclassing the
HttpServletResponse object and wrapping the original response.
Intercept a Servlet's invocation after the servlet is called
The designers of Servlet Filters identified the following examples for their use:
1. Authentication Filters.
2. Logging and Auditing Filters.
3. Image conversion Filters.
4. Data compression Filters.
5. Encryption Filters
6. Tokenizing Filters
1. Filters that trigger resource access events
2. XSL/T filters
3. Mime-type chain Filter
Filer Life Cycle
public interface Filter {
public void init(FilterConfig filterConfig);
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain);
public void destroy(); }
init( ) : called when the filter is initialized and loaded into memory by the Servlet
container; called when the filter is being put into service.
doFilter( ) : called by the Servlet container each time a request/response pair is
passed through the chain due to a client request for a resource at the end of the chain.

71
The FilterChain passed in to this method allows the Filter to pass on the request and
response to the next entity in the chain.
destroy( ) : called just prior to the filter being removed from memory; called when
the filter is being taken out of service.
The init and destroy methods manage an internal FilterConfig member variable
The following two sections were added to web deployment descriptor that parallel the
Servlet descriptors:
filter: defines a unique filter name and the fully qualified class name that it references
filter-mapping: maps URLs to filters
In Web.xml Add the following
<filter>
<filter-name>TimerFilter</filter-name>
<filter-class>com.informit.webtechnologies.TimerFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>TimerFilter</filter-name>
<url-pattern>/* </url-pattern>
</filter-mapping>
Event Listeners
Servlet context-level (application-level) event --> This involves resources or state
held at the level of the application servlet context object.
Session-level event --> This involves resources or state associated with the series of requests
from a single user session; that is, associated with the HTTP session object.
At each of these two levels, there are two event categories:
1. Lifecycle changes
2. Attribute changes
Event Category Event Descriptions Interface
Servlet context
lifecycle changes
Servlet context creation, at which point the first request can be serviced
Imminent shutdown of the servlet context
javax.servlet.ServletContextListener
Servlet context attribute changes
Addition of servlet context attributes javax.servlet.
ServletContextAttributeListener
Event Category Event Descriptions Interface
Removal of servlet context attributes
Replacement of servlet context attributes
Session lifecycle changes
Session creation
Session invalidation
Session timeout
javax.servlet.http.
HttpSessionListener
Session attribute changes
Addition of session attributes
Removal of session attributes

72
Replacement of session attributes
javax.servlet.http.
HttpSessionAttributeListener
Typical Event Listener Scenario
The listener is notified of application startup.
The application logs in to the database and stores the connection object in the servlet
context.
Servlets use the database connection to perform SQL operations.
The listener is notified of imminent application shutdown (shutdown of the Web server or
removal of the application from the Web server).
Prior to application shutdown, the listener closes the database connection.
Event Listener Declaration and Invocation In web.xml
<web-app>
<listener>
<listener-class>com.acme.MyConnectionManager</listenerclass>
</listener>
<listener>
<listener-class>com.acme.MyLoggingModule</listener-class>
</listener>
</web-app>
In a multithreaded application, attribute changes might occur simultaneously. There is no
requirement for the servlet container to synchronize the resulting notifications; the listener
classes themselves are responsible for maintaining data integrity in such a situation.
Each listener class must have a public zero-argument constructor.
Each listener class file must be packaged in the application WAR file, either under /WEBINF/
classes or in a JAR file in /WEB-INF/lib.
ServletContextListener Methods, ServletContextEvent Class
The ServletContextListener interface specifies the following methods:
void contextInitialized(ServletContextEvent sce) --> The servlet container calls
this method to notify the listener that the servlet context has been created and the
application is ready to process requests.
void contextDestroyed(ServletContextEvent sce) --> The servlet container calls this method to
notify the listener that the application is about to be shut down.
ServletContext getServletContext() --> The servlet container creates a
javax.servlet.ServletContextEvent object that is input for calls to ServletContextListener methods.
ServletContextAttributeListener Methods, ServletContextAttributeEvent Class
The ServletContextAttributeListener interface specifies the following methods:
void attributeAdded(ServletContextAttributeEvent scae) --> The servlet container calls this
method to notify the listener that an attribute was added to the servlet context.
void attributeRemoved(ServletContextAttributeEvent scae)--> The servlet container calls
this method to notify the listener that an attribute was removed from the servlet context.
void attributeReplaced(ServletContextAttributeEvent scae) --> The servlet container calls
this method to notify the listener that an attribute was replaced in the servlet context.
The container creates a javax.servlet.ServletContextAttributeEvent object that is input for
calls to ServletContextAttributeListener methods. The ServletContextAttributeEvent class
includes the following methods, which your listener can call:
String getName() --> Use this to get the name of the attribute that was added, removed,
or replaced.

73

Object getValue() --> Use this to get the value of the attribute that was added, removed,
or replaced. In the case of an attribute that was replaced, this method returns the old
value, not the new value.
HttpSessionListener Methods, HttpSessionEvent Class
The HttpSessionListener interface specifies the following methods:
void sessionCreated(HttpSessionEvent hse) --> The servlet container calls this method to
notify the listener that a session was created.
void sessionDestroyed(HttpSessionEvent hse) --> The servlet container calls this method to notify
the listener that a session was destroyed.
The container creates a javax.servlet.http.HttpSessionEvent object that is input for calls to
HttpSessionListener methods. The HttpSessionEvent class includes the following method,
which your listener can call:
HttpSession getSession() --> Use this to retrieve the session object that was created or
destroyed, from which you can obtain information as desired. See HttpSessionAttributeListener Methods,
HttpSessionBindingEvent Class
The HttpSessionAttributeListener interface specifies the following methods:
void attributeAdded(HttpSessionBindingEvent hsbe) --> The servlet container calls this method to
notify the listener that an attribute was added to the session.
void attributeRemoved(HttpSessionBindingEvent hsbe) --> The servlet container calls this
method to notify the listener that an attribute was removed from the session.
void attributeReplaced(HttpSessionBindingEvent hsbe) --> The servlet container calls this
method to notify the listener that an attribute was replaced in the session.
The container creates a javax.servlet.http.HttpSessionBindingEvent object that is input for
calls to HttpSessionAttributeListener methods. The HttpSessionBindingEvent class includes
the methods that follow, which your listener can call.
String getName() --> Use this to get the name of the attribute that was added, removed, or replaced.
Object getValue() --> Use this to get the value of the attribute that was added, removed, or replaced.
In the case of an attribute that was replaced, this method returns the old value, not the new value.
HttpSession getSession() --> Use this to retrieve the session object that had the attribute change.
Event Listener Sample
This section provides code for a sample that uses a servlet context lifecycle and session
lifecycle event listener. This includes the following components:
SessionLifeCycleEventExample: This is the event listener class, implementing the
ServletContextListener and HttpSessionListener interfaces.
SessionCreateServlet: This servlet creates an HTTP session.
SessionDestroyServlet: This servlet destroys an HTTP session.
index.jsp: This is the application welcome page (the user interface), from which you can
invoke SessionCreateServlet or SessionDestroyServlet.
web.xml: This is the deployment descriptor, where the servlets and listener class are

74
declared. Welcome Page: index.jsp
Here is the welcome page, the user interface that enables you to invoke the session-creation
servlet by clicking the Create New Session link, or to invoke the session-destruction servlet
by clicking the Destroy Current Session link. <%@page session="false" %> <H2>OC4J HttpSession Event Listeners </H2>
<P>
This example demonstrates the use of the HttpSession Event and Listener that is
new with the Java Servlet 2.3 API.
</P>
<P>
[<a href="servlet/SessionCreateServlet">Create New Session</A>] &nbsp;
[<a href="servlet/SessionDestroyServlet">Destroy Current Session</A>]
</P>
<P>
Click the Create link above to start a new HttpSession. An HttpSession listener has been configured for
this application. The servler container will send an event to this listener when a new session is created or
destroyed. The output from the event listener will be visible in the
console window from where OC4J was started.
</P>
JSP
<% scriplets (what code puts here is executed in sevice() %>
<HTML>
<BODY>
<%
System.out.println( "Evaluating date now" );
java.util.Date date = new java.util.Date(); %>
Hello! The time is now
<%
out.println( date );
out.println( "<BR>Your machine's address is " );
out.println( request.getRemoteHost()); %>
</BODY>
</HTML>
<% ! declaration (any variable declared here is globally accessable, can contain static
& instance variables) %>
<%= expression (assign any expression ,fire in System.out.println();) %>
--> @ the time of translation container convert JSP into a servlet
<% @ directive (page ,include ,tagLib %>
<% @ page %>

--> static add content from file @ translation time


--> Page specific properties such as character encoding.

<% @ tagLib tagdir=\web-inf\tags\coolprefix=cool%> --> include Directory


<% @ include filename=fileName%> --> include etxt and code at translation time.
<!-- comment [ <%= expression %> ] -->
Action Tags
<% jsp:some-Action %>
< jsp:useBean id=persontype=classtypeclass=classnamescope=/ >
id--> identifier for bean object
type / class --> any one of the two is necessary.

75

< jsp:plugin type = bean/applet name=instance_name/ >


< jsp:getProperty name =property= < >/ jsp:setProperty>
name --> identify actual bean object with useBean tag.
Property --> property name in setter & getter in bean.
< jsp:setProperty name =property=value=/>
< jsp:include page= x.jsp>--> happens At runtime
--> powerful can reach outside web application.
< jsp:forward page=x.jsp>--> buffer is cleared before forward.
< jsp:param name=namevalue=/>
JSP Life Cycle
1. Translation Phase
2. Request Processing Phase.
3. Instantiate and loading Phase
4. JspInit()
_Jsp Service() // _JspService() JspService cannot be over ridden its final
5. JspDestroy()
<% while(str!=null) % {> <% system.out.println(Str); } % >
Include multiple pages using jsp:Include
session.getattribute ()
append the value in the jsp url
its works same was as jsp include can you give me its syntax
but jsp include u can include only 1 jsp
Implicit Objects in JSP
1. Request --> Javax.servlet.http.httpservletrequest
2. Response --> Javax.servlet.http. httpservletresponse
3. Session --> Javax.servlet.http.httpsession
4. Application --> Javax.servlet.http.ServletContext
5. Out --> Javax.servlet.jsp.JspWriter
6. Page --> used to call any methods defined by the servlet class.
7. PageContext --> Access to information associated with a request. Used in Parameter & cookies
8. Config --> Stores the Servlet configuration data
9. Exception --> Java.lang.throwable
scope of variable --> page , request , session ,Application --> global.
Default value of Scope --> Page
Include Directive ( < % @/ > )
<JSP:Include>
at the time of translation include a page.
include the page at the time of compilation.
Will not affect at request time
Change will affect request time.
Static
Dynamic.
Java Bean
Taglib.
Serializable
Cant serializable
4 scope include request,res,page,app
Only Page
jsp / servlet.
Support only JSP

76

Include Directive ( < % @ page /> )


Page directives
<%@pageLanguage=java%>
<%@pageimport=pkg.*%>
<%@pageextendspkg.class%>
<%@pageSession=true/false%>
<%@pageautoflush=true/false%>
<%@pageisthreadSafetrue/false%>
<%@pageinfo=text%>
<%@pageerrorPage=errorpage.jsp%>
<%@ page iserrorPage=true/false(or)errorpage.jsp%>
<%@pagecontenttype=text/html(or)application/jar%>
<%@ page buffer = 8Kb %>
<%@pageisELIgnored=True/False%>--> check for Expr Language.
Store data in a XML file.
InitParam --> Only for a particular application.
<initParam>
<initParamName>email-id</initParamName>
<initParamvalue>kannan@rediffmail.com</initParamvalue>
</initparam>
ContextParam --> access for all or common applications.
<contextParam>
<contextParamName>email-id</contentParamName>
<contextParamvalue> kannan@rediffmail.com</contentParamvalue>
</contextparam>
JAAS --> Java Authorization and Authentication Service
TYPE 1 : in WEB.XML
<error-page>
<exception-type>UnhandledException</exception-type>
<location>UnhandledException.jsp</location>
</error-page>
TYPE 2 : errorpage , iserrorPage= true errorPage = *.jsp
<%@ page errorPage="exceptionHandler.jsp" %>
VALUES CHANGE FROM HTML TO JSP
HTML CODE
<html>
<head>
<style>body, input { font-family:Tahoma; font-size:8pt; } </style>
</head>
<body>
<table align="center" border=1>
<form action="formHandler.jsp" method="post">
<tr><td>Enter your first Number: </td>

77
<td><input type="text" name="fno" /></td></tr>
<tr><td>Enter your Second Number: </td>
<td><input type="text" name="sno" /></td></tr>
<tr ><td colspan="2"><input ty
pe="submit" value="Submit" /></td></tr>
</form>
</table>
</body></html>
1. JSP CODE
<%@ page errorPage="exceptionHandler.jsp" %>
<html>
<head>
<style> body, p { font-family:Tahoma; font-size:10pt; }</style>
</head><body>
<%
int fno;
int sno;
fno = Integer.parseInt(request.getParameter("fno"));
sno = Integer.parseInt(request.getParameter("sno"));
int div=fno/sno;
%>
<p>Division is : <%= div %></p>
<p><a href="form.html">Back</a>.</p>
</body>
</html>
2. ERROR PAGE
<%@ page isErrorPage="true" import="java.io.*" %>
<html>
<head>
<title>Exceptional Even Occurred!</title>
<style> body, p { font-family:Tahoma; font-size:10pt;padding-left:30; }
pre { font-size:8pt; } </style>
</head>
<body>
<%-- Exception Handler --%>
<font color="red">
<%= exception.toString() %><br>
</font>
<%
out.println("<!--");
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
exception.printStackTrace(pw);
out.print(sw);
sw.close();
pw.close();
out.println("-->");
%>
</body>
</html>
DISPLAY DATA FROM A ARRAYLIST IN HTML /JSP PAGE

78
ArrayList arrName =(ArrayList)request.getAttribute("Del_Mgr_on");
for(int i=0;i<name.size();i++) {
out.println(arrName.get(i));
}
Here Del_Mgr_on should be Name that you set in your previous page using
setAttribute("Del_Mgr_on",ArrayListName);
Display Values from a Hashmap
// Action code
Map<String,String> map = new HashMap<String,String>();
mapOnValueStack = map;
//add key/value pairs
fieldKeyOnValueStack = "1";//sets key
In Display using JSTL
<s:property value="%{mapOnValueStack.['fieldKeyOnValueStack']}" />
Display values from a RESULTSET JDBC
<%@page import="java.sql.*"%>
<table border=1>
<tr><th>Name</th><th>Address</th></tr>
<%
try{ Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root","root");
Statement st=con.createStatement();
ResultSet rs=st.executeQuery("select * from data");
while(rs.next()){ %>
<tr><td><%=rs.getString("name")%></td><td><%=rs.getString("address")%></td></tr> <% }
rs.close();
st.close();
con.close();
} catch(Exception e){} %>
</table>
TO Include a Logo right through the application
GetPageContext().include("hello.jsp");
Examples <jsp:setProperty name= "mybean" property="* " />
<jsp:setProperty name= "mybean" property= "username" />
<jsp:setProperty name= "mybean" property= "username" value="Steve" />
Description
The <jsp:setProperty> element sets the value of one or more properties in a Bean, using the
Bean's setter methods.
You must declare the Bean with < jsp:useBean> before you set a property value with
< jsp:setProperty>. Because <jsp:useBean> and <jsp:setProperty> work together, the Bean instance
names they use must match (that is, the value of name in <jsp:setProperty> and the value of id in
<jsp:useBean> must be the same).
<jsp:useBean
id= "beanInstanceName"

79
scope="page | request | session | application"
{
class="package.class" |
type= "package.class" |
class="package.class" type="package.class" |
beanName="{ package.class | <%= expression %>} "
type="package.class"
}

{
/> > other elements </jsp:useBean>
}

Examples
<jsp:useBean id= "cart" scope="session" class="session.Carts" />
<jsp:setProperty name= "cart" property="* " />
<jsp:useBean id= "checking" scope="session" class= "bank.Checking" >
<jsp:setProperty name= "checking" property="balance" value="0.0" />
</jsp:useBean>
Description
The <jsp:useBean> element locates or instantiates a JavaBeans component. <jsp:useBean>
first attempts to locate an instance of the Bean. If the Bean does not exist, < jsp:useBean>
instantiates it from a class or serialized template.
To locate or instantiate the Bean, < jsp:useBean> takes the following steps, in this order:
1. Attempts to locate a Bean with the scope and name you specify.
2. Defines an object reference variable with the name you specify.
3. If it finds the Bean, stores a reference to it in the variable. If you specified type, gives
the Bean that type.
4. If it does not find the Bean, instantiates it from the class you specify, storing a
reference to it in the new variable. If the class name represents a serialized template,
the Bean is instantiated by java.beans.Beans.instantiate.
5. If < jsp:useBean> has instantiated (rather than located) the Bean, and if it has body
tags or elements (between <jsp:useBean> and </ jsp:useBean>), executes the body
tags.
JSP <jsp:getProperty name="beanInstanceName"property="propertyName"/>
Examples --> <jsp:useBean id= "calendar" scope= "page" class="employee.Calendar" />
<h2>
Calendar of < jsp:getProperty name= "calendar" property="username" />
</h2>
Description The <jsp:getProperty> element gets a Bean property value using the property's getter
methods and displays the property value in a JSP page. You must create or locate a Bean
with <jsp:useBean> before you use <jsp:getProperty>.
The <jsp:getProperty> element has a few limitations you should be aware of:
1. You cannot use < jsp:getProperty> to retrieve the values of an indexed property.
2. You can use < jsp:getProperty> with JavaBeans components, but not with
enterprise beans. As alternatives, you can write a JSP page that retrieves values from a
Bean that in turn retrieves values from an enterprise bean, or you can write a custom tag
that retrieves values from an enterprise bean directly.
Description
The <jsp:plugin> element plays or dispays an object (typically an applet or Bean) in the
client Web browser, using a Java plug-in that is built in to the browser or downloaded from a specified
URL.

80
When the JSP file is translated and compiled and Java and sends back an HTML response to
the client, the < jsp:plugin> element is replaced by either an <object> or <embed> element,
according to the browser version. The <object> element is defined in HTML 4.0 and
<embed> in HTML 3.2.
<jsp:include page="scripts/login.jsp" />
<jsp:include page="copyright.html" />
<jsp:include page="/index.html" />
<jsp:include page="scripts/login.jsp">
<jsp:param name="username" value="jsmith" />
</jsp:include>
<jsp:forward page="/servlet/login" />
<jsp:forward page="/servlet/login">
<jsp:param name= "username" value="jsmith" />
</jsp:forward>
Description
The <jsp:forward> element forwards the request object containing the client request
information from one JSP file to another file. The target file can be an HTML file, another JSP file, or a
servlet, as long as it is in the same application context as the forwarding JSP file.
The lines in the source JSP file after the <jsp:forward> element are not processed.
<%! int i = 0; %>
<%! int a, b, c; %>
<%! Circle a = new Circle(2.0); %>
Description
A declaration declares one or more variables or methods that you can use in JavaTM code later in the JSP
file. You must declare the variable or method before you use it in the JSP file. You can declare any
number of variables or methods within one declaration element, as long as you end each declaration with
a semicolon. The declaration must be valid in the Java programming language.
<%-- This comment will not be visible in the page source --%>
JSP JSTL Tags.
<%@ taglib
prefix="c"

uri="http://java.sun.com/jstl/core" %>

Core Tags :
Gen purpose
< c:out>
--> print
Example
<form method=post action="demo1.jsp">
NAME <input type=text name="text1"><br>
NAME:<c:out value="${param.text1}" /><br>
<c:setvar(reqd)scope(optional)value(doesnthavestring)/>--> set property of bean & map
values
< c:remove> --> remove when something is wrong.
< c:catch> --> like try / catch
Conditonal
< c:if> -->doesnthaveelse.nowayexactlytosay
Example
<select
name="combo1">
<option
value="sam">sam
<c:if test="${seq'sam'[or]s==sam>"}
<c:out
value="Good Morning...SAM!" />
< c:choose> -->
< c:when> --> All refers to Switch case Block

81
< c:otherwise> -->
Example
<c:choose >
<c:when
test=" "
>
<c:otherwise> something </c:otherwise>
</c:choose>
<c:choose>
<c:when test="${s==1}">Sunday </c:when>
<c:when test="${s==2}">Monday</c:when>
<c:when test="${s==3}">Tuesday</c:when>
<c:when test="${s==4}">Wednesday</c:when>
<c:when test="${s==5}">Thursday</c:when>
<c:otherwise>
select between 1 & 5
URL Related.
< c:import>
--> add content to JSP from another resource
--> add content @ request time
Example
<c:import url="welcome.htm"/>
< c:URL> --> link URL for all hyperlinks
Example :
<a
href="<c:url value="http://localhost:8080/welcome.htm/>">
< c:redirect > --> redirect to another page
Example :
<c:redirect url="http://localhost:8080/welcome.htm />
< c:param> --> uses to replace both url rewriting and encoding
Iteration
< c:forEach> --> simple way to iterate array and collections
Example
<% pageContext.setAttribute("colors",new String[] {"red","green","blue","orange"} ); %>
<table> <c:forEach var="n" items="${colors}" varStatus="a">
<c:forEach var="n" begin="3" end="8" > <c:out value="${n}" /> <br></c:forEach>
< c:forTokens> --> like stringTokenizier
Example:
<c:forTokens
items="${s}"
/></td> </c:forTokens>

delims="," var="token" >

Formatting tags Internationalization


< fmt:message>
< fmt:setLocale>
< fmt:bundle>
< fmt:setBundle>
< fmt:param>
< fmt:requestEncoding>
Formatting
< fmt:timeZone>
< fmt:setTimeZone>
< fmt:formatNumber>
< fmt:parseNumber>
< fmt:parseDate>

<td><c:out value="${token}"

82
SQL
< SQL:Query>
< SQL:Update>
< SQL:setDataSource>
< SQL:Param>
< SQL:DataParam>
Example
<sql:setDataSource var="db" driver="sun.jdbc.odbc.JdbcOdbcDriver" url="jdbc:odbc:dbdemo"/>
<sql:query var="query1" dataSource="${db}" sql="${s}"
/>
XML

< x: Parse>
< x: choose>
< x: when>
< x: otherwise>
< x: forEach>
Example
xsl1.xsl
=======
<?xml version="1.0"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:template match="/">
<html>
<body>
<table border="2" bgcolor="yellow">
<tr>
<th>Name</th>
<th>Place</th>
<th>Number</th>
<th>Mark</th>
</tr>
<xsl:for-each select="students/student">
<tr>
<td><xsl:value-of
select="name"/> </td>
<td><xsl:value-of
select="place"/> </td>
<td><xsl:value-of
select="number"/> </td>
<td><xsl:value-of
select="mark"/> </td>
</tr>
</xsl:for-each>
</table>
</body>
</html>
</xsl:template>
</xsl:stylesheet>
Transform-action
< x:transform>
< x: param>
TagHandler
Tech both jsp container container
<%@taglibPrefix=mineuri=randomtesting>
3 ways to include content

83
1. < % @ include >
< % jsp: Action I nclude >
2. < c:param> replaces Param
3. < c:URL> whatever the hyperlink needs.
Thread safe
for jsp we have page isthreadsafe=true;
for servlet singlethreadmodel
singlethreadmodel is deprecated

synchronize the service method multiple threads will access single instance of the servlet at the
time of execution of a thread.
JSP Paging
<pagination-tag:pager start="<%=start%> " range="<%=range%>"
results= "<%=results%> "/>
<%@ taglib uri="http://paginationtag.miin.com" prefix="pagination-tag"%> or
<%@ taglib uri="/WEB-INF/pagination.tld" prefix="pagination-tag"%> (provided you drop
the tld in the /WEB-INF/)
< jsp:setProperty name="beanInstanceName"
{
property= "* " |
property="propertyName" [ param= "parameterName" ] |
property="propertyName" value="{ string | <%= expression %>} "
}
/>
<%@ page session= false >
One reason would be performance and memory. If you have a page that doesn't need to be involved
in a session (like say, an about.jsp or faq.jsp) then the default behaviour of involving every JSP in a
session will impose the overhead of creating a new session object (if one doesn't already exist) and
increased memory usage as more objects reside on the heap.
This effect will be greatly exaggerated in case of a single page seeing high traffic from many unique
users combined with a high bounce rate i.e. they users do not continue to browse but leave the site
immediately after viewing that one page- the container will create a new session object per user which
will never be used again and will ultimately be garbage collected after it times out - added over head of
object creation, memory usage and garbage collection without giving you any real value.
You can declare methods for use within your JSP page as declarations. The methods can then be invoked
within any other methods you declare, or within JSP scriptlets and expressions.
<%!
public String whereFrom(HttpServletRequest req) {
HttpSession ses = req.getSession();
...
return req.getRemoteHost();
}
%>
<% out.print("Hi there, I see that you are coming in from "); %>
<%= whereFrom(request) %>
DEPLOYMENT PROCESS FOR DIFFERENT WEB / APP SERVERS.
1. TOMCAT:

84
1. set JAVA_HOME=C:\jdk1.x.xx in AutoExec.bat or Environment Variables.
2. c:\tomcat 5.x.x /bin> Startup / Catalina start
3. deploy java class files in c:\tomcat\webapps\user defined folder\classes
4. TOMCAT --> WEB-APPS --> USER-DEFINED-FOLDER --> WEB-INF --> CLASSES
5. Change Port no in Tomcat --> tomcat/server/conf.xml --> change port no.
6. Change user details --> tomcat-users.xml <role -------/>
7. http://localhost/user-defined folder/ filename(servlet / filename.jsp).
8. c:/tomcat 5.x.x/bin/shutdown.
Java Session is stored in the Container
On Executing more than 1 tomcat with same port-no will result in binding exception at a
time. On executing more than 1 tomcat with different port-no works fine at a time.A tomcat
version 4.x support servlet 2.3 & JSP 1.2 whereas Tomcat 5.x support servlet 2.4 & jsp 2.0
2. JRUN EXECUTION PROCESS
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.

C:\jrun\bin> jrun commands inJRUN


Enter into a screen -start -nohup
--> Enter Admin Login & PWD -stop -config
--> Enter Home page -restart -version
--> Add JRUN Server -status -build
--> [top menu] create new server name -Info
--> give servername & port no.
(note for each project Port no is different)
For New Server
--> c:\jrun\server \ create new server
--> Enter project name
--> default ear \ server-INF
--> default EJB default-War \ META-INF
--> paste all files & moify the property files.
ECLI PSE I DE --> load the project with ANT as Build.xml
Java Project --> Existing ANT File (Build.xml).
Type Project Name --> select build.xml --> finish.

3. Weblogic Deployment Process


The following documentation assumes that a WebLogic 8.1 server has been installed and you have built
the application specific archive for deployment on weblogic 8.1
If you do not want internationalization support then skip first two steps.
1. Following changes are required to support internationalization in application using Maker-Checker
functionality. Place "weblogic.xml" file in "\Web-inf" folder with application home folder set in
packager tool with following content:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE web-app PUBLIC '-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN'
'http://java.sun.com/dtd/web-app_2_3.dtd'>
<web-app id="WebApp_ID">
<charset-params>
<input-charset>
<resource-path>/*</resource-path>
<java-charset-name>UTF-8</java-charset-name>
</input-charset>
</charset-params>
</web-app>

85
Note: If you alreadyhaveweblogic.xmlin\Web-inffolder,thencopythetags-values of <charsetparams>.
2. Re-Build J2EE archive to build your application deployable using packager tool.
3. From web-logic directory, open startWebLogic.cmd(NT) or startWebLogic.sh(UNIX) in a text editor.
Ensure that the respective database specific driver jars are in class-path as listed below and should
be in class-path before the weblogic specific jars:
ORACLE Specific
DB2 Specific

Classes14.jar
db2jcc.jar,
db2jcc_license_cisuz.jar,
db2jcc_license_cu.jar

4. Start the WebLogic server.


5. Start the WebLogic console. (http://<ip>:<port>/console)
6. ThefirstactivityistocreateaConnectionPool.
i)
From the menu in the left-hand side pane, navigate to
<domainname>ServicesJDBCConnectionPool
ii)
ClickConfigureanewJDBCConnectionPool
iii)
Choose the relevant database type in the Database Type drop down box. (for MLSAMPLEAPP
application,valueshouldbeORACLE)
iv)
Select the relevant database driver from the list of Database Drivers andclickonContinue.
(ForClass4driverbasedapplication,valueshouldbeOraclesDriver(Thin)
Versions:8.1.7,9.0.1,9.0.2).
ForDB2SelectIBMsDB2Drivers(Type2)version7.x.8.x
v)
Fill in the following in the window that is shown.
Name
Database Name
Host Name
Port
Database User Name
and Password
vi)
vii)

viii)
ix)
x)
xi)

<ConnectionPoolName>
<Name of your database>
<Database Host / Machine Name>
<Database Port> (Default value is 1521) this step
is not required for DB2
< Database User Name and Password>

Click Continue to create the Connection Pool.


For DB2, provide the following information
DriverClassName:com.ibm.db2.jcc.DB2Driver
URL
:jdbc:db2://<ipaddress>:50000/<schemaname>
Note: DB2 default port is 50000.
ClicktheTestDriverConfiguration(ifyouwanttotesttheconnection)orclickSkipthis
testbuttonandthenclickonCreateanddeploybutton.
Click on newly created pool name. Click on connections tab. Change the initial capacity to 2.
NavigatetoMonitoring
Check whether the just created pool is mentioned in this list. If it is present, it means that
the connection pool has been created properly. If it is not present, then there has been some
error creating the pool. Check whether all the above instructions have been followed. Check
WebLogic console and WebLogic logs for error.

7. ThenextactivityistocreateaTransactionalDataSource.
i)
Inthemenunavigateto<domainname>ServicesJDBCDataSource.
ii)
ClickConfigureanewJDBCDataSource.
iii)
Fill in the following in the window that is shown.

86
Name
JNDI Name

<TxDataSourceName>
<Any name> (This must match the name given in
the<DataSourceJNDI>tagintheconfiguration
file required by <ApplicationName>.xml file)
E.g. while deploying MLSAMPLEAP, the value of
<DataSourceJNDI>inMLSAMPLEAPP.xmlis
mlPool.
iv)
ClickContinueandselectthepoolname(createdinstep7)fromthedropdown.
v)
ClickContinueandverifythatcheckboxischeckedagainstyourservername.Clickon
CreatetocreatetheData Source.
vi)
A new Transactional Data Source has now been created.
8. The final activity is to deploy the Application component i.e. <applicationName>.ear (ear which is
generated by tool and put in the distribution folder. This ear also contains the jar file for the sample
entity i.e. EntityClasses.jar)
i)
Inthemenunavigateto<domainname>DeploymentApplications.
ii)
ClickonDeployanewApplication.
iii)
Intheresultingscreenclickonuploadyourfile(s)linkandthenBrowseandnavigateto
the location of DIST_HOME and select EAR archive to be deployed.
iv)
NowclickonUpload.
v)
After uploading, one entry would appear for MLSAMPLEAPP.ear with radio button.
vi)
SelecttheradiobuttonandclickonContinue.
vii)
Confirmation page will be displayed before deploying the application.ClickDeploybuttonto
deploy the application.
viii)
IntheresultantpageStatusofActionshouldbeseenasSuccess(itmighttakesometime
so please wait or refresh the page if it is taking too much of time).
ix)
Navigateto<domainname>DeploymentApplicationsMLSAMPLEAPP MLAppCore
from the menu.
x)
Intheresultingscreen,clickonMonitoring
xi)
CheckthatRequestSessionispresentintheensuinglist.
xii)
Navigateto<domainname>DeploymentApplicationsMLSAMPLEAPP MLAppServlets
from the menu.
xiii)
Intheresultingscreen,clickonMonitoring Servlets
xiv)
Checkthat/Log4jLoaderispresentintheensuinglist.
Websphere Application Server WAS Admin console
Use the administrative console to configure connection pooling
1. Start the HTTP Server Administration interface.
2. Click the Manage tab.
3. Select your application server from the Server list.
4. Enable the adminconsole application if it is not already enabled.
a. In the navigation menu, click Manage installed applications.
b. Select the adminconsole application.
c. Click Properties.
d. For Application Enablement, select Enabled.
5. To start your application server, click the Start button (
) at the top of navigation menu. If
your application server is running, you must stop it and restart it.
6. In the navigation menu, click Launch Express Console.
7. When prompted, enter a user ID. The WebSphere administrative console is displayed in the
browser window.
Note: The user ID does not need to be an OS/400 user profile. This user ID is used only to
track which users make changes to the application server configuration.

87
You can also start the console without starting the HTTP Server Administration interface. To use this
method, follow these steps:
1. Start the HTTP Server Administration interface.
2. Click the Manage tab.
3. Select your application server from the Server list.
4. Enable the adminconsole application if it is not already enabled.
a. In the navigation menu, click Manage installed applications.
b. Select the adminconsole application.
c. Click Properties.
d. For Application Enablement, select Enabled.
5. To start your application server, click the Start button (
) at the top of navigation menu. If
your application server is running, you must stop it and restart it.
6. Open this URL in your browser:
http://your.server.name:port/admin
where your.server.name is the host name of the iSeries server on which your application server
is running, and port is the WebSphere administrative console port as noted in the ready
message in the joblog of your application server. This port is also specified in the admin_host
virtual host.
7. When prompted, enter a user ID. The WebSphere administrative console is displayed in the
browser window.
Note: The user ID does not need to be an OS/400 user profile. This user ID is used only to
track which users make changes to the application server configuration.
1. Expand Resources and click JDBC Providers.
2. Click the name of the JDBC provider that is associated with the data source for which you want
to configure connection pooling.
3. Click Data Sources.
4. On the Data Sources page, click the name of the data source for which you want to configure
connection pooling.
5. Click Connection Pool.
6. On the Connection Pools page, configure connection pooling settings.
7. Click Apply or OK.
8. Save the application server configuration.
Use wsadmin to configure connection pooling
To configure connection pooling with wsadmin, follow these steps:
1. On the OS/400 command line, run the STRQSH (Start Qshell) command.
2. Run the cd command to change to the directory that contains the wsadmin tool:
cd /QIBM/ProdData/WebASE/ASE5/bin
3. Start wsadmin.
4. At the wsadmin prompt, run this command to identify the parent ID:
5. set newds [$AdminConfig getid
6. /Cell:myCell/Node:myNode/Server:myAppSvr/
JDBCProvider:JDBC1/DataSource:DS1/]
where myCell is the name of the cell that contains your application server, myNode is the name
of the node that contains your application server, myAppSvr is the name of your application
server, JDBC1 is the name of your JDBC provider, and DS1 is the name of your the data source
for which you want to create a connection pool.
Note: This command has been wrapped for display purposes.
7. Run this command to create a new connection pool:
$AdminConfig create ConnectionPool $newds {}
8. Run this command to save your changes:
$AdminConfig save

88

JBOSS APP SERVER


Jboss 4.0.5-GA
The following documentation assumes that Jboss 4.0.5-GA(integrated with tomcat 5.5) server has been
installed and you have built the application specific archive for deployment. If not please refer to chapter
3 section 3.2.1 for the same.
1. a)ForOracle,createanxmlfilewithnameoracle-ds.xmlandaddthebelowentriestoit.
<?xml version="1.0" encoding="UTF-8"?>
<datasources>
<local-tx-datasource>
<jndi-name>mlPool</jndi-name>
<use-java-context>false</use-java-context>
<track-connection-by-tx/>
<isSameRM-override-value>false</isSameRM-override-value>
<driver-class>oracle.jdbc.driver.OracleDriver</driver-class>
<connection-url>jdbc:oracle:thin:@<ip address>:<port no>:<sid></connection-url>
<user-name>abc</user-name>
<password>abc123</password>
<min-pool-size>5</min-pool-size>
<max-pool-size>10</max-pool-size>
</local-tx-datasource>
</datasources>
b) ForDB2,createanxmlfilewithnamedb2-ds.xmlandaddthebelowentriestoit
<?xml version="1.0" encoding="UTF-8"?>
<datasources>
<local-tx-datasource>
<jndi-name>mlPool</jndi-name>
<use-java-context>false</use-java-context>
<track-connection-by-tx/>
<isSameRM-override-value>false</isSameRM-override-value>
<driver-class>com.ibm.db2.jcc.DB2Driver</driver-class>
<connection-url>jdbc:db2://<ip address>:<port no.>/<SID></connection-url>
<user-name>abc</user-name>
<password>abc123</password>
<min-pool-size>5</min-pool-size>
<max-pool-size>10</max-pool-size>
</local-tx-datasource>
</datasources>
Note: Change the <connection-url>, <user-name>,

<password> , <jndi-name> tag as per

your requirement.
2. Placethefilecreatedinstep1intothe<JbossHome>\server\<server name>\deployfolder.
Copythebelowsaidfileintothe<JbossHome>\server\<server name>\libfolder.
ORACLE Specific

Classes14.jar

DB2 Specific

db2jcc.jar,

89
db2jcc_license_cisuz.jar,
db2jcc_license_cu.jar
3. Copytheapplicationspecificarchivefileinto<JbossHome>\server\<server name>\deployfolder.
4. Changethe<attributename="UseJBossWebLoader">valuetotrueinthejboss-service.xmlfile
withinthe<JbossHome>\<server name>\default\deploy\jbossweb-tomcat55.sar\META-INFfolder.
ForWar:valueoftagshouldbetrue
ForEar:valueoftagshouldbefalse
5. Start the JBoss application server.
Deployment Location : Server Default Deploy WAR / EAR .
WAS INTEGRATION
to right click the WAS and select admin console.

Step 5: To create new data sources for IMO projects like (edwAAAMDS_DEV, mssr3).
Step 6: To give Scope, Provider, Name, JNDI Name, Data store helper class, Database Name, Server
Name, Port Number.

90
Step 7: To select JAAS - J2C authentication data then given Component-managed authentication alias (eg
: SSC66472Node01/EDWDEMO) ,user id and password.

Step 8: To click the test connection button it will come successfully created JNDI msg.
Step 9: To set the property files location and jar files location in server environment below mentioned
the steps.
Step 10: Create a custom property under Application servers > server1 > Process Definition >
Java Virtual Machine > Custom Properties> name : widPropertiesFile
C:\*WS\Java\IMO\wid_51.properties

91

Step 11: <In the class-path under Application servers > server1 > Process Definition > Java Virtual
Machine Add the class path entry for C:\JavaJars\Shared_CFI_Lib\widFramework.jar
(C:\JavaJars\Shared_CFI_Lib\widFramework.jar;C:\JavaJars\UserSessionEJB.jar;C:\JavaJa
rs\UserSessionEJBEAR.ear;C:\JavaJars\Shared_CFI_Lib\log4j1.2.14.jar;C:\JavaJars\netscapesdk.jar;C:\JavaJars\PwMatrix.jar;C:\JavaJars\Shared_CFI_
Lib\ORACLE\ojdbc14.jar;C:\JavaJars\Shared_CFI_Lib\Sybase\jconn2.jar)
Step 12: To Define a widLogRoot in locally. Like (C:\SureshWS\Java\IMO\wid.log)
Step 13: To Set environment variables
Variable Name: myss.env.propertyfile
Variable Value: C:\John Hancock\myss.properties

92

JMS CONFIG in JBOSS


The file jbm-jms.xml on the server classpath contains any JMS Queue, Topic and ConnectionFactory
instances that we wish to create and make available to lookup via the JNDI.
A JMS ConnectionFactory object is used by the client to make connections to the server. It knows the
location of the server it is connecting to, as well as many other configuration parameters. In most cases
the defaults will be acceptable.
We'll deploy a single JMS Queue and a single JMS Connection Factory instance on the server for this
example but there are no limits to the number of Queues, Topics and Connection Factory instances you
can deploy from the file. Here's our configuration:
<configuration xmlns="urn:jboss:messaging"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="urn:jboss:messaging ../schemas/jbm-jms.xsd ">
<connection-factory name="ConnectionFactory">
<connector-ref connector-name="netty"/>
<entries>
<entry name="ConnectionFactory"/>
</entries>
</connection-factory>

93

<queue name="OrderQueue">
<entry name="queues/OrderQueue"/>
</queue>
</configuration>
Deploy one ConnectionFactory called ConnectionFactory and bind it in just one place in JNDI as
given by the entry element. ConnectionFactory instances can be bound in many places in JNDI
When using JNDI from the client side need to specify a set of JNDI properties which tell the JNDI client
where to locate the JNDI server, amongst other things. These are often specified in a file called
jndi.properties on the client classpath, or you can specify them directly when creating the JNDI initial
context.
java.naming.factory.initial=org.jnp.interfaces.NamingContextFactory
java.naming.provider.url=jnp://myhost:1099
java.naming.factory.url.pkgs=org.jboss.naming:org.jnp.interfaces

Where myhost is the hostname or IP address of the JNDI server. 1099 is the port used by the JNDI
server and may vary depending on how you have configured your JNDI server.
In the default standalone configuration, JNDI server ports are configured in the jbm-jboss-beans.xml file
where the JNDIServer bean is confgured, here's a snippet from the file:
<bean name="JNDIServer" class="org.jnp.server.Main">
<property name="namingInfo">
<inject bean="Naming"/>
</property>
<property name="port">1099</property>
<property name="bindAddress">localhost</property>
<property name="rmiPort">1098</property>
<property name="rmiBindAddress">localhost</property>
</bean>
JBOSS INTEGRATION
JNDI
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
// in main()
Hashtable env = new Hashtable();
env.put(Context.INITIAL_CONTEXT_FACTORY,"com.sun.jndi.fscontext.RefFSContextFactory");
Context ctx = new InitialContext(env);
Object obj = ctx.lookup(name);
try {
Context ctx = new InitialContext(env);
// Create the initial context
Object obj = ctx.lookup(name); // Look up an object
System.out.println(name + " is bound to: " + obj);
} catch (NamingException e) {
System.err.println("Problem looking up " + name + ": " + e);
}

94
JNDI Directory using LDAP
import javax.naming.Context;
import javax.naming.directory.InitialDirContext;
import javax.naming.directory.DirContext;
import javax.naming.directory.Attributes;
import javax.naming.NamingException;
// in main()
Hashtable env = new Hashtable();
env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
env.put(Context.PROVIDER_URL, "ldap://localhost:389/o=JNDITutorial");
//With this configuration, this command queries the LDAP server on machine localhost that is listening on
// port 389, serving the "o=JNDITutorial" namespace
DirContext ctx = new InitialDirContext(env);
Attributes attrs = ctx.getAttributes("cn = Ted Geisel, ou=People");
attrs.get("sn").get();
try {
DirContext ctx = new InitialDirContext(env); // Create the initial directory context
Attributes attrs = ctx.getAttributes("cn=Ted Geisel, ou=People"); // Ask for all attributes of the object
System.out.println("sn: " + attrs.get("sn").get()); // Findsurname attribute ("sn") and print it
} catch (NamingException e) {
System.err.println("Problem getting attribute:" + e);
}
DeployTool deployment Process
1. Introduction
a. Read this dialog to learn more about the wizard.
b. Click Next.
2. WAR File dialog
a. In the Module File Name field, enter MyHello.war.
b. In the War Display Name field, enter MyHelloWAR.
c. Click Edit.
3. Edit Contents dialog
a. Navigate to the following directory, which contains the service interface and implementation
class.
<JWSDP_HOME>/docs/tutorial/examples/jaxrpc/dephello/
build/shared
b. Add HelloIF.class and HelloImpl.class to the field labelled Contents of MyHelloWAR.
c. Click OK.
d. Click Next.
4. Choose Component Type dialog
a. Select the JAX-RPC Endpoint radio button.
b. Click Next.
5. JAX-RPC Default Settings dialog
a. In the WSDL Target Namespace Base String field, enter the following:
http://wombat.com/wsdl/
b. In the Schema Target Namespace Base String field, enter the following:
http://wombat.com/xsd/
c. In the Endpoint Alias Base String field, enter /jaxrpc.
d. Click Next.
6. JAX-RPC Endpoint dialog

95
a. In the EndPoint Interface combo box, select dephello.HelloIF.
b. In the EndPoint Class combo box, select dephello.HelloImpl.
c. In the Endpoint Name field, enter MyHelloWorld.
d. In the Endpoint Display Name field, enter MyHelloWorld.
e. Leave the Alias field blank.
f. Click Next.
7. JAX-RPC Model dialog
a. Select the Use Default Settings radio button.
b. Click Next.
8. Review Settings dialog
a. Take a quick look at the two XML files displayed by this dialog. The file shown at the top of the
dialog is the web.xml file that will be packaged in the WAR file. The file displayed at the bottom
is the jaxrpc-ri.xml file, also to be packaged in the WAR file. The jaxrpc-ri.xml file is
implementation-specific and is not defined by the specifications.
b. Click Finish.
The deploytool utility now creates the MyHello.war file.
ORACLE
SQL
Data Definition Language (DDL) contains the commands used to create and destroy databases
DDL Commands : CREATE,ALTER,DROP,TRUNCATE,COMMENT,RENAME
Data Manipulation Language is used to insert, retrieve and modify the data contained
within the table.
DML Commands: SELECT,INSERT,UPDATE,DELETE,MERGE - UPSERT,CALL,EXPLAIN
PLAN,LOCK TABLE
DCL involves operation of granting permission and some operations related to control the
database
DCL Commands: GRANT,REVOKE
The USE Command is used to specify the database to work.
A cluster is a group of documents similar to each other in content.Clustering is also known
as unsupervised classification.
Character functions that return number values can take as their argument any character
datatype.
Single-row functions return a single result row for every row of a queried table or view.
Aggregate functions return a single result row based on groups of rows, rather than on
single rows.
Conversion functions convert a value from one datatype to another
Use the PARTITI ON BY clause to partition the query result set into groups based on one or
more value_expr.
combine multiple queries using the set operators UNION, UNION ALL, INTERSECT, and
MINUS. All set operators have equal precedence.
Operation acts from left to right.
The set operators are not valid on columns of type BLOB, CLOB, BFILE, VARRAY, or nested
table.
The UNION, INTERSECT, and MINUS operators are not valid on LONG columns
If the select list preceding the set operator contains an expression,then you must provide a
column alias for the expression in order to refer to it in the order_by_clause.

96
Usage of UNION Eliminates duplicate (distinct ) selected rows.
A join is a query that combines rows from two or more tables, views, or materialized views.
To execute a join of three or more tables, Oracle first joins two of the tables based on the
join conditions comparing their columns and then joins the result to another table based on
join conditions containing columns of the joined tables and the new table.
An equi-join is a join with a join condition containing an equality operator. An equi join
combines rows that have equivalent values for the specified columns.
A self join is a join of a table to itself
If two tables in a join query have no join condition, then Oracle returns their Cartesian
product.
An inner join (sometimes called a "simple join") is a join of two or more tables that returns
only those rows that satisfy the join condition.
An outer join extends the result of a simple join. An outer join returns all rows that satisfy
the join condition and also returns some or all of those rows from one table for which no
rows from the other satisfy the join condition.
To write a query that performs an outer join of tables A and B and returns all rows from A (a
left outer join), use the LEFT [OUTER] JOIN syntax in the FROM clause, or apply the outer
join operator (+) to all columns of B in the join condition in the WHERE clause.
To write a query that performs an outer join of tables A and B and returns all rows from B (a
right outer join), use the RIGHT [OUTER] JOIN syntax in the FROM clause, or apply the
outer join operator (+) to all columns of A in the join condition in the WHERE clause.
ALTER CLUSTER statement to redefine storage and parallelism characteristics of a cluster.
ALTER SESSION statement to specify or modify any of the conditions or parameters that
affect your connection to the database
CREATE CLUSTER statement to create a cluster.
A cluster is a schema object that contains data from one or more tables, all of which have
one or more columns in common.
A cursor is a variable that runs through the tuples of some relation. This relation can be a
stored table, or it can be the answer to some query.
A procedure is introduced by the keywords CREATE PROCEDURE followed by the procedure
name and its parameters
Procedure
Procedure return any number of values
Inner Join
An inner join will return a row only if there is a
joined row with data in both tables- being
joined

Function
Function can return only one value.
Outer Join
An outer join will return a row even if the other
table doesn't have a corresponding row

A primary key is a single field or combination of fields that uniquely defines a record. None
of the fields that are part of the primary key can contain a null value. A table can have only
one primary key.
A foreign key means that values in one table must also appear in another table.
A composite key is combination of 2 or 3 fields in a table.
A Trigger is used to check a condition.
A Trigger is executed every time when the particular table is executed.It is required to

97
execute it only once.it will automatically executed everytime when database is invoked.
I ndex refers to as a key to table records ,it is stored in sorted order.for easy and fast
accessing of records.
The SQL OUTER JOIN clause is a variation of the SQL JOIN clause enables a SELECT statement to access
more than one table. The JOIN clause controls how tables are linked. It is a qualifier of the SQL FROM
clause.
The OUTER JOIN clause differs from the standard JOIN clause (also known as the INNER JOIN clause) in
that rows are returned even when there are no matches through the JOIN critieria on the second able.

For Optimizing a Query


1. Apply Index.
2. Remove left outer join.
To select n max(sal) from table t1,t2
Select sal from table t1 where (n-1) =(select count (distinct (sal)) from table t2 where t1.sal >t2.sal.
ORACLE SQL QUERI ES
1. Physical Level --> Organize & Store raw Data
2. Conceptual Level --> isolate Data Storage Details
3. Extenal Level --> Varying View of application to different users.
Normalization
Key --> Uniquely Identified row in table
Intelligentr Key --> Keys based on data values
Non Intelligent Key --> to identify Row
Relationships
One to One
One to Many
Many to Many
Normalization Forms
First NF --> Elimination of Repeated Groups
Second NF --> Eliminate Redundant Data
Third NF --> Eliminate Column Not dependent on Keys
Fourth NF --> Isolate independent Multiple relationships
Fifth NF --> Isolate Semantically related multiple relationships
De-normalization --> to improve performance using frequently performed calculations.
SQL Literals
CHARACTER(n) --> fixed Length of String
n> 0 --> Integer --> char
Char Varying (n) --> Vary Length string max length n
Similarly Bit, Bit Varying
Numeric(P,Q) --> P--> Digits Q--> Digits After Decimal Points
Integer --> Signed Integer Decimal / Binary

98
Float(p) --> Floating Point Number
SQL Operators
Unary --> + , Binary --> * , /
Comparison
= --> equality
!= , < >, --> Not EQUAL
--> G.T
< --> L.T
>= --> G.E
<= --> L.E
IN --> in any member of
NOT IN --> Not in any Member of
Is NULL , --> allow the field as null
is Not NULL --> allow the field not as nulls
Exists --> Check the execution of SubQuery is not EMPTY
LIKE -->likestartswith1stCharacterm
Like E% --> 1st letter is E
Like %E% --> have letter E
IN --> Compare More than 1 Check Condition
Between --> Two value ranges
Also Not Between
Logical Operators --> Single result from combining 2 separate conditions
And --> both condition should be true
OR --> Either of the condition
NOT --> return true if condition is false
SET OPERATOR
UNION --> All distinctr rows from both queries (main query & Sub Query)
UNIONALL --> Return all rows from both queries
Intersect --> Return queries match both queries
Minus --> All distinct rows of first query not in 2nd .
Inbuilt Functions
ABS(-146) = 146
ABS(146) = 146
CEIL (2) = 2; CEIL(1.3) = 2; CEIL(-1.3) = 2;
FLOOR(2) = 2; FLOOR(1.3) = 1;
MOD(100,3) = 1; MOD(22,33) = 22;
POWER(3,2) = 9; POWER(4, .5) = 2;
SQRT(4) = 2; SQRT(-4) = NULL
EXP(5)=148.4134.
LN(3) = 1.098612
LOG(10,100) = 2
ROUND(33,33,3) = 33.33; ROUND(66.666,2) = 66.68
TRUNC(66.666,2) = 66.66; TRUNC (22.1,0) = 22;

99
SIGN(146) = 1; SIGN(-146)= -1; SIG(0) = 0;
SIN(VALUE); COS(VALUE); TAN(VALUE);
AVG(10,10,10) = 10;
LI ST
Greatest (VAL1 ,VAL2,VAL3); --> pick greatest Value
Least(VAL1,VAL2,VAL3); --> Pick Least Value
AGGREGATE Functions
COUNT() --> Select Count(* ) from Table-Name
SUM () --> Select SUM(C1) from Table-Name
AVG() --> Select AVG(C1) from Table-Name
MAX() --> Select MAX(C1) from Table-Name
MIN() --> Select MIN(C1) from Table-Name
Data Definition Language (DDL)
CREATE TABLE , VIEW , INDEX
ALTER TABLE,
DROP Table, View, Index
Data Manipulation Language (DML)
INSERT
UPDATE
DELETE
Data Control Language(DCL)
GRANT
REVOKE
DELETE
DATA Query Language (DQL)
SELECT
Data Administration Statements (DAS)
START AUDIT
STOP AUDIT
Transaction Control Statements (TCL)
COMMIT
ROLLBACK
SAVEPOINT
SETTRANSACTION
CREATE TABLE
Create Table Table-Name(Col1DataTypeNOTNULL,..PRIMARYKEY(COL1));
MODIFY
Alter table Table-Nameaddcolumn..
DELETE TABLE

100
Drop Table Table-Name
Index --> Index can speed execution of SQL With Condition
Create Index Index-Name on Table-Name (Column [order]) --> Asc(default)
--> Desc
Composite Index --> involves more than 1 column
Unique Index --> Prevent Duplication of Data
Clustered Index --> Sorted both Logically & Physically.
--> Created on Primary Key
Create index I1 on Employee (c1,c2); c1,c2 --> Columns in table Employee
Drop Index Index-Name;
Views -->namedTable,wontPhysicallySeparateDatadefineinterimofothertable
( base table )
Create View View-Name as Sub-Query
Can be used for multiple queries
Both Updatable & nonUpdatable
NULL --> Values desired
Insert into Table-Name[Column List ];
Update Table set Column =Update table-Name Where Condition;
Delete from Table-Name Condition;
Select Trunc(* ) from Table-Name --> Deletes the entire data leaves Table Structure alone.
Cast --> Scalar value to scalar Data-Type
Cast (scalar-exp) as { Data-Type }
CASE
When Cond-Exp then Scalar exp
Else
scalar Exp
end;
INDICATOR --> null indicator variable parameter sent to -1
SELECT --> Select ( all / Distinct) exp (Query) from Table-Name; Where Condition Group By
--> Usually refers for Aggregate functions / Columns
--> Having --> include certain Groups ,Equivalent to [ where ]
--> Order By --> Sort by Order --> Asc [default]
--> Desc [descending Order ]
Select Distinct (* ) from Table-Name --> Eliminate Duplicates
Select * from Table-Name where year in (1993,1996,1999);
--> check if it matches year values given
Select * from Table-Name where year not in (1993,1996,1999);
check if it not matches year values given.

101
Select * from Table-Name where C1 between [2 specific values ] Or Using Sub-Queries Correlated sub
Query
--> execute Outer Query first , Sub-Query Next Usual
--> Sub Query Executed first then outer query .
Parallel Sub Query
--> More than 1 sub query in a query.

Join
EQUI-JOIN --> comparison operator is equality
Non EQUI-JOIN--> comparison operator is not equal sign
Natural Join --> produce result that contain 2 identical rows ,1 row being Eliminated
Self Join --> A Table joined with Itself
Outer Join --> Extended Inner Join
Table are joined contain matching values both matching & non matching rows returned.
LEFT Outer Join --> Use Keyword LEFT [OUTER] or (*)
RIGHT Outer Join --> use keyword Right [OUTER]
FULL Outer Join --> use (+)
Grant Permission
Grant (All/Privilege)
On { Table Name Column-Name VIEW NAME }
To { PUBLIC /USER LIST }
With Grant option
Public --> to all users of the system
ALL --> all Privileges
With Grant --> All users can access Privileges
REVOKE --> Take away privileges given by Grant
Revoke { Privileges List / ALL }
On Table /Coloumn /View }
From { Public /User List }
I ntegrity Constraints --> restrict data values that can be inserted into database
that could be inserted into database that could be deleted & Modified.
Referential
Entity
Create Assertation check (not Exists (cond));
Domain
Create Domain D-Name as Defn
Alter Domain D-NameAdd../Drop
Candidate Key --> unique identifier ( a column or combination of columns) of table
Foreign Key --> a column or combination of column in one table ,values required to match
some candidate key in another table

102
Lock

--> On Reading Data


--> on Updating Data
Exclusive Lock --> during data modification on insert / delete / update
Update --> no access to other users
Shared Lock --> read only access to other users.
Trigger. --> An action database should take PL / SQL Code
--> Need to be executed only once and will get invoked automatically till dropped
Row Level Trigger --> once Fro each row of transaction
Statement Level Trigger --> Execute once for each transaction
Before Trigger , After Trigger
Create or Replace Trigger Trigger-Name
Before /After
Delete / INSERT / UPDATE
On [USER] Table-Name
For Each Row
[PL/SQL Block]
Backup:
COMMIT;
ROLLBACK;
SavePoint --> A point on transaction That you can rollback without rollback entire transaction.
SavePoint sp1
SQL1;
..
SavePoint sp2
SQL2;
Rollback sp2; --> rollback SP2
ORACLE
SQL
TYPES OF KEYS IN ORACLE
super key : all attributes that are select to make a primary key are known as super key.
primary key:-attribute that uniquely identified a row in a table is known as primary key and primary
key shuld be unique and not null.
candidate key:-remaining all the keys which are not select to a primary key are known as candidate
key(alternate key).
composit key :-when mare than one field choose to make a primary key then, that keys are known
as composit key.
ORACLE SQL QUERI ES
1. Physical Level --> Organize & Store raw Data
2. Conceptual Level --> isolate Data Storage Details

103
3. Extenal Level --> Varying View of application to different users.

Normalization
Key --> Uniquely Identified row in table
Intelligentr Key --> Keys based on data values
Non Intelligent Key --> to identify Row
Relationships
One to One
One to Many
Many to Many
Normalization Forms
First NF --> Elimination of Repeated Groups
Second NF --> Eliminate Redundant Data
Third NF --> Eliminate Column Not dependent on Keys
Fourth NF --> Isolate independent Multiple relationships
Fifth NF --> Isolate Semantically related multiple relationships
De-normalization --> to improve performance using frequently performed calculations.
Data Definition Language (DDL) contains the commands used to create and destroy databases
DDL Commands :
CREATE,
create table iot_ (
a number,
b varchar2(10),
constraint pk_iot_ primary key (a, b)
)
ALTER,
ALTER TABLE table_name
RENAME TO new_table_name;
ALTER TABLE table_name
ADD column_name column-definition;
ALTER TABLE table_name
MODIFY column_name column_type;
ALTER TABLE table_name
DROP COLUMN column_name;
truncate table table_name;
truncate cluster cluster_name;
Delete
The DELETE command is used to remove rows from a table. A WHERE clause can be used to only
remove some rows. If no WHERE condition is specified, all rows will be removed. After performing a
DELETE operation you need to COMMIT or ROLLBACK the transaction to make the change permanent or
to undo it. Note that this operation will cause all DELETE triggers on the table to fire.
SQL> SELECT COUNT(*) FROM emp;
SQL> DELETE FROM emp WHERE job = 'CLERK';
TRUNCATE
TRUNCATE removes all rows from a table. The operation cannot be rolled back and no triggers will be
fired. As such, TRUCATE is faster and doesn't use as much undo space as a DELETE.

104

SQL> TRUNCATE TABLE emp;


Table truncated.
DROP
The DROP command removes a table from the database. All the tables' rows, indexes and privileges will
also be removed. No DML triggers will be fired. The operation cannot be rolled back.
SQL> DROP TABLE emp;
DROP and TRUNCATE are DDL commands, whereas DELETE is a DML command. Therefore DELETE
operations can be rolled back (undone), while DROP and TRUNCATE operations cannot be rolled back.
DML Commands:
Select
SELECT department_id, job_id INTO deptid, jobid

FROM employees WHERE employee_id = 140;

Insert
INSERT INTO suppliers (supplier_id, supplier_name) SELECT account_no, name FROM customers
WHERE city = 'Newark';
MERGE:
MERGE
INTO target_table tgt
USING source_table src ON
( src.object_id = tgt.object_id ) WHEN MATCHED
THEN UPDATE SET tgt.object_name = src.object_name ,
tgt.object_type = src.object_type
WHEN NOT MATCHED THEN INSERT ( tgt.object_id ,
tgt.object_name , gt.object_type )
VALUES ( src.object_id , src.object_name , src.object_type );
Update multiple rows of data..
UPDATE CLASSCONVENINGS
SET ACITVE_FLG = 2
WHERE
CLASS_CONVENE_DATE = TO_DATE('2005-12-31 00:00:00',
'YYYY-MM-DD HH24:MI:SS')
/
COMMIT WORK ;
/
UPSERT
create or replace procedure ups(xa number) as
begin
merge into mergetest m using dual on (a = xa)
when not matched then insert (a,b) values (xa,1)
when matched then update set b = b+1; end ups;
/ drop table mergetest;
create table mergetest(a number, b number);
call ups(10); call ups(10); call ups(20);
select * from mergetest
DCL involves operation of granting permission and some operations related to control the
database

105
DCL Commands: GRANT,REVOKE
Join
EQUI-JOIN --> comparison operator is equality
Non EQUI-JOIN--> comparison operator is not equal sign
Natural Join --> produce result that contain 2 identical rows ,1 row being Eliminated
Self Join --> A Table joined with Itself
Outer Join --> Extended Inner Join
Table are joined contain matching values both matching & non matching rows returned.
LEFT Outer Join --> Use Keyword LEFT [OUTER] or (*)
RIGHT Outer Join --> use keyword Right [OUTER]
FULL Outer Join --> use (+)
Grant Permission
Grant (All/Privilege)
On { Table Name Column-Name VIEW NAME }
To { PUBLIC /USER LIST }
With Grant option
Public --> to all users of the system
ALL --> all Privileges
With Grant --> All users can access Privileges
REVOKE --> Take away privileges given by Grant
Revoke { Privileges List / ALL }
On Table /Coloumn /View }
From { Public /User List }
I ntegrity Constraints --> restrict data values that can be inserted into database
that could be inserted into database that could be deleted & Modified.
Referential
Entity
Create Assertation check (not Exists (cond));
Domain
Create Domain D-Name as Defn
Alter Domain D-NameAdd../Drop
Candidate Key --> unique identifier ( a column or combination of columns) of table
Foreign Key --> a column or combination of column in one table ,values required to match
some candidate key in another table
Lock

--> On Reading Data


--> on Updating Data

Exclusive Lock --> during data modification on insert / delete / update


Update --> no access to other users
Shared Lock --> read only access to other users.
Trigger. --> An action database should take PL / SQL Code
--> Need to be executed only once and will get invoked automatically till dropped
Row Level Trigger --> once Fro each row of transaction
Statement Level Trigger --> Execute once for each transaction

106
Before Trigger , After Trigger
Create or Replace Trigger Trigger-Name
Before /After
Delete / INSERT / UPDATE
On [USER] Table-Name
For Each Row
[PL/SQL Block]
Backup:
COMMIT;
ROLLBACK;
SavePoint --> A point on transaction That you can rollback without rollback entire transaction.
SavePoint sp1
SQL1;
..
SavePoint sp2
SQL2;
Rollback sp2; --> rollback SP2
String DataTypes
CONCATINATION | | STRING | | STRING2
RPAD & LPAD --> Pad right side with any set of characters.
LTRIM --> delete unwanted character on left end of string.
RTRIM --> delete unwanted character on right end of string
Length (string) --> 6
SUBSTR(String, Start[count]); --> generate substring from start.
INSTR(String, Set[,start[ocandea]); --> insert a string at desired Location.
SOUNDEX --> Compare sound entry in selected coloumn
Dates
ADD_MONTHS (PDate ,2); PDATE --> Present date in Table
Least
Greatest
DUAL --> Inbuilt Table provides with 1 row & 1 column initialized by Oracle.
NEXT_DAY
LAST_DAY
MONTHS_BETWEEN
TO_DATE
ROUND
TRUNC
TO-CHAR
NEW-DATE
SYNONYM --> Alias Name to Object.
Create Synonym emp for emp1.employee select * from empl.employee --> replace emp in table name;
Drop Synonym emp;
SNAPSHOT --> Read Only Table
Simple SnapShot
Complex SnapShot
Create SnapShot emp;
EXECUTE Immediate --> Prepare / Execute Statement.

107

DECLARE --> Define a CURSOR


OPEN --> Define a executable statement
FETCH --> Return Data from Resultant Table
CLOSE --> Release all resources.
For Nth Highest salary
SELECT DISTINCT (a.sal) FROM EMP A WHERE &N = (SELECT COUNT (DISTINCT (b.sal)) FROM EMP B
WHERE a.sal<=b.sal);
JOINS:
SQL JOIN
The JOIN keyword is used in an SQL statement to query data from two or more tables, based on a
relationship between certain columns in these tables.
Tables in a database are often related to each other with keys.
A primary key is a column (or a combination of columns) with a unique value for each row. Each primary
key value must be unique within the table. The purpose is to bind data together, across tables, without
repeating all of the data in every table.
Look at the "Persons" table:
P_Id

LastName

FirstName

Address

City

Hansen

Ola

Timoteivn 10

Sandnes

Svendson

Tove

Borgvn 23

Sandnes

Pettersen

Kari

Storgt 20

Stavanger

Note that the "P_Id" column is the primary key in the "Persons" table. This means that no two rows can
have the same P_Id. The P_Id distinguishes two persons even if they have the same name.
Next, we have the "Orders" table:
O_Id

OrderNo

P_Id

77895

44678

22456

24562

34764

15

Note that the "O_Id" column is the primary key in the "Orders" table and that the "P_Id" column refers to
the persons in the "Persons" table without using their names.
Notice that the relationship between the two tables above is the "P_Id" column.
Different SQL JOINs
Before we continue with examples, we will list the types of JOIN you can use, and the differences
between them.
JOIN: Return rows when there is at least one match in both tables
LEFT JOIN: Return all rows from the left table, even if there are no matches in the right table
RIGHT JOIN: Return all rows from the right table, even if there are no matches in the left table
FULL JOIN: Return rows when there is a match in one of the tables

SQL INNER JOIN Keyword

The INNER JOIN keyword return rows when there is at least one match in both tables.
SQL INNER JOIN Syntax

108

SELECT column_name(s)
FROM table_name1
INNER JOIN table_name2
ON table_name1.column_name=table_name2.column_name
PS: INNER JOIN is the same as JOIN.

SQL INNER JOIN Example


The "Persons" table:
P_Id

LastName

FirstName

Address

City

Hansen

Ola

Timoteivn 10

Sandnes

Svendson

Tove

Borgvn 23

Sandnes

Pettersen

Kari

Storgt 20

Stavanger

The "Orders" table:


O_Id

OrderNo

P_Id

77895

44678

22456

24562

34764

15

Now we want to list all the persons with any orders.


We use the following SELECT statement:
SELECT Persons.LastName, Persons.FirstName, Orders.OrderNo
FROM Persons INNER JOIN Orders
ON Persons.P_Id=Orders.P_Id
ORDER BY Persons.LastName
The result-set will look like this:
LastName

FirstName

OrderNo

Hansen

Ola

22456

Hansen

Ola

24562

Pettersen

Kari

77895

Pettersen

Kari

44678

The INNER JOIN keyword return rows when there is at least one match in both tables. If there are rows
in "Persons" that do not have matches in "Orders", those rows will NOT be listed.

SQL LEFT JOIN Keyword

The LEFT JOIN keyword returns all rows from the left table (table_name1), even if there are no matches
in the right table (table_name2).
SQL LEFT JOIN Syntax
SELECT column_name(s)
FROM table_name1
LEFT JOIN table_name2
ON table_name1.column_name=table_name2.column_name
PS: In some databases LEFT JOIN is called LEFT OUTER JOIN.

109

SQL LEFT JOIN Example


The "Persons" table:
P_Id

LastName

FirstName

Address

City

Hansen

Ola

Timoteivn 10

Sandnes

Svendson

Tove

Borgvn 23

Sandnes

Pettersen

Kari

Storgt 20

Stavanger

The "Orders" table:


O_Id

OrderNo

P_Id

77895

44678

22456

24562

34764

15

Now we want to list all the persons and their orders - if any, from the tables above.
We use the following SELECT statement:
SELECT Persons.LastName, Persons.FirstName, Orders.OrderNo
FROM Persons
LEFT JOIN Orders
ON Persons.P_Id=Orders.P_Id
ORDER BY Persons.LastName
The result-set will look like this:
LastName

FirstName

OrderNo

Hansen

Ola

22456

Hansen

Ola

24562

Pettersen

Kari

77895

Pettersen

Kari

44678

Svendson

Tove

The LEFT JOIN keyword returns all the rows from the left table (Persons), even if there are no matches in
the right table (Orders).

SQL RIGHT JOIN Keyword

The RIGHT JOIN keyword returns all the rows from the right table (table_name2), even if there are no
matches in the left table (table_name1).
SQL RIGHT JOIN Syntax
SELECT column_name(s)
FROM table_name1
RIGHT JOIN table_name2
ON table_name1.column_name=table_name2.column_name
PS: In some databases RIGHT JOIN is called RIGHT OUTER JOIN.

SQL RIGHT JOIN Example


The "Persons" table:
P_Id

LastName

FirstName

Address

City

110
1

Hansen

Ola

Timoteivn 10

Sandnes

Svendson

Tove

Borgvn 23

Sandnes

Pettersen

Kari

Storgt 20

Stavanger

The "Orders" table:


O_Id

OrderNo

P_Id

77895

44678

22456

24562

34764

15

Now we want to list all the orders with containing persons - if any, from the tables above.
We use the following SELECT statement:
SELECT Persons.LastName, Persons.FirstName, Orders.OrderNo
FROM Persons
RIGHT JOIN Orders
ON Persons.P_Id=Orders.P_Id
ORDER BY Persons.LastName
The result-set will look like this:
LastName

FirstName

OrderNo

Hansen

Ola

22456

Hansen

Ola

24562

Pettersen

Kari

77895

Pettersen

Kari

44678
34764

The RIGHT JOIN keyword returns all the rows from the right table (Orders), even if there are no matches
in the left table (Persons).

SQL FULL JOIN Keyword

The FULL JOIN keyword return rows when there is a match in one of the tables.
SQL FULL JOIN Syntax
SELECT column_name(s)
FROM table_name1
FULL JOIN table_name2
ON table_name1.column_name=table_name2.column_name

SQL FULL JOIN Example


The "Persons" table:
P_Id

LastName

FirstName

Address

City

Hansen

Ola

Timoteivn 10

Sandnes

Svendson

Tove

Borgvn 23

Sandnes

Pettersen

Kari

Storgt 20

Stavanger

The "Orders" table:

111
O_Id

OrderNo

P_Id

77895

44678

22456

24562

34764

15

Now we want to list all the persons and their orders, and all the orders with their persons.
We use the following SELECT statement:
SELECT Persons.LastName, Persons.FirstName, Orders.OrderNo
FROM Persons
FULL JOIN Orders
ON Persons.P_Id=Orders.P_Id
ORDER BY Persons.LastName
The result-set will look like this:
LastName

FirstName

OrderNo

Hansen

Ola

22456

Hansen

Ola

24562

Pettersen

Kari

77895

Pettersen

Kari

44678

Svendson

Tove
34764

The FULL JOIN keyword returns all the rows from the left table (Persons), and all the rows from the right
table (Orders). If there are rows in "Persons" that do not have matches in "Orders", or if there are rows
in "Orders" that do not have matches in "Persons", those rows will be listed as well.

The SQL UNION Operator

The UNION operator is used to combine the result-set of two or more SELECT statements.
Notice that each SELECT statement within the UNION must have the same number of columns. The
columns must also have similar data types. Also, the columns in each SELECT statement must be in the
same order.
SQL UNION Syntax
SELECT column_name(s) FROM table_name1
UNION
SELECT column_name(s) FROM table_name2
Note: The UNION operator selects only distinct values by default. To allow duplicate values, use UNION
ALL.
SQL UNION ALL Syntax
SELECT column_name(s) FROM table_name1
UNION ALL
SELECT column_name(s) FROM table_name2
PS: The column names in the result-set of a UNION are always equal to the column names in the first
SELECT statement in the UNION.

112
SQL UNION Example
Look at the following tables:
"Employees_Norway":
E_ID

E_Name

01

Hansen, Ola

02

Svendson, Tove

03

Svendson, Stephen

04

Pettersen, Kari

"Employees_USA":
E_ID

E_Name

01

Turner, Sally

02

Kent, Clark

03

Svendson, Stephen

04

Scott, Stephen

Now we want to list all the different employees in Norway and USA.
We use the following SELECT statement:
SELECT E_Name FROM Employees_Norway
UNION
SELECT E_Name FROM Employees_USA
The result-set will look like this:
E_Name
Hansen, Ola
Svendson, Tove
Svendson, Stephen
Pettersen, Kari
Turner, Sally
Kent, Clark
Scott, Stephen
Note: This command cannot be used to list all employees in Norway and USA. In the example above we
have two employees with equal names, and only one of them will be listed. The UNION command selects
only distinct values.

SQL UNION ALL Example


Now we want to list all employees in Norway and USA:
SELECT E_Name FROM Employees_Norway
UNION ALL
SELECT E_Name FROM Employees_USA
Result
E_Name
Hansen, Ola
Svendson, Tove

113
Svendson, Stephen
Pettersen, Kari
Turner, Sally
Kent, Clark
Svendson, Stephen
Scott, Stephen
The SQL SELECT INTO Statement
The SELECT INTO statement selects data from one table and inserts it into a different table.
The SELECT INTO statement is most often used to create backup copies of tables.
SQL SELECT INTO Syntax
We can select all columns into the new table:
SELECT *
INTO new_table_name [IN externaldatabase]
FROM old_tablename
Or we can select only the columns we want into the new table:
SELECT column_name(s)
INTO new_table_name [IN externaldatabase]
FROM old_tablename
SQL SELECT INTO Example
Make a Backup Copy - Now we want to make an exact copy of the data in our "Persons" table.
We use the following SQL statement:
SELECT *
INTO Persons_Backup
FROM Persons
We can also use the IN clause to copy the table into another database:
SELECT *
INTO Persons_Backup IN 'Backup.mdb'
FROM Persons
We can also copy only a few fields into the new table:
SELECT LastName,FirstName
INTO Persons_Backup
FROM Persons
SQL SELECT INTO - With a WHERE Clause
We can also add a WHERE clause.
The following SQL statement creates a "Persons_Backup" table with only the persons who lives in the city
"Sandnes":
SELECT LastName,Firstname
INTO Persons_Backup
FROM Persons

114

WHERE City='Sandnes'
SQL SELECT INTO - Joined Tables
Selecting data from more than one table is also possible.
The following example creates a "Persons_Order_Backup" table contains data from the two tables
"Persons" and "Orders":
SELECT Persons.LastName,Orders.OrderNo
INTO Persons_Order_Backup
FROM Persons
INNER JOIN Orders
ON Persons.P_Id=Orders.P_Id
The CREATE DATABASE Statement
The CREATE DATABASE statement is used to create a database.
SQL CREATE DATABASE Syntax
CREATE DATABASE database_name
CREATE DATABASE Example
Now we want to create a database called "my_db".
We use the following CREATE DATABASE statement:
CREATE DATABASE my_db
Database tables can be added with the CREATE TABLE statement.
SQL NOTNULL
CREATE TABLE Persons
(
P_Id int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255)
)
To select n max(sal) from table t1,t2
Select sal from table t1 where (n-1) =(select count (distinct (sal)) from table t2 where t1.sal >t2.sal.
PL/SQL
The Declaration section (optional).
The Execution section (mandatory).
The Exception (or Error) Handling section (optional).
Declaration Section:
The Declaration section of a PL/SQL Block starts with the reserved keyword DECLARE. This section is
optional and is used to declare any placeholders like variables, constants, records and cursors, which are
used to manipulate data in the execution section. Placeholders may be any of Variables, Constants and
Records, which stores data temporarily. Cursors are also declared in this section.
Execution Section:

115
The Execution section of a PL/SQL Block starts with the reserved keyword BEGIN and ends with END.
This is a mandatory section and is the section where the program logic is written to perform any task.
The programmatic constructs like loops, conditional statement and SQL statements form the part of
execution section.
Exception Section:
The Exception section of a PL/SQL Block starts with the reserved keyword EXCEPTION. This section is
optional. Any errors in the program can be handled in this section, so that the PL/SQL Blocks terminates
gracefully. If the PL/SQL Block contains exceptions that cannot be handled, the Block terminates abruptly
with errors.
Every statement in the above three sections must end with a semicolon ; . PL/SQL blocks can be nested
within other PL/SQL blocks. Comments can be used to document code.
This is how a sample PL/SQL Block looks.
DECLARE
Variable declaration
BEGIN
Program Execution
EXCEPTION
Exception handling
END;
DECLARE
salary number(4);
deptvarchar2(10)NOTNULL:=HRDept;
DECLARE
var_salary number(6);
var_emp_id number(6) = 1116;
BEGIN
SELECT salary
INTO var_salary
FROM employee
WHERE emp_id = var_emp_id;
dbms_output.put_line(var_salary);
dbms_output.put_line('The employee '
|| var_emp_id || ' has salary ' || var_salary);
END;
Constants:
DECLARE
salary_increase CONSTANT number (3) := 10;
IF ELSE COND:
IF condition 1
THEN
statement 1;
statement 2;
ELSIF condtion2 THEN
statement 3;
ELSE
statement 4;

116
END IF;
LOOP IN PLSQL
1. LOOP
statements;
EXIT;
{or EXIT WHEN condition;}
END LOOP;
2. WHILE <condition>
LOOP statements;
END LOOP;
3. FOR counter IN val1..val2
LOOP statements;
END LOOP
CURSOR :
A cursor is a temporary work area created in the system memory when a SQL statement is
executed. A cursor contains information on a select statement and the rows of data accessed by it. This
temporary work area is used to store the data retrieved from the database, and manipulate this data. A
cursor can hold more than one row, but can process only one row at a time. The set of rows the cursor
holds is called the active set.
TYPES :
Implicit Cusrors.
These are created by default when DML statements like, INSERT, UPDATE, and DELETE
statements are executed. They are also created when a SELECT statement that returns just one row is
executed.
DECLARE var_rows number(5);
BEGIN
UPDATE employee
SET salary = salary + 1000;
IF SQL%NOTFOUND THEN
dbms_output.put_line('None of the salaries where updated');
ELSIF SQL%FOUND THEN
var_rows := SQL%ROWCOUNT;
dbms_output.put_line('Salaries for ' || var_rows || 'employees are updated');
END IF;
END;
Attributes used for
Attributes
%FOUND
%NOTFOUND
%ROWCOUNT

117

EXPLICIT CURSORS:
They must be created when you are executing a SELECT statement that returns more than one row.
Even though the cursor stores multiple records, only one record can be processed at a time, which is
called as current row. When you fetch a row the current row position moves to next row.
DECLARE the cursor in the declaration section.
OPEN the
cursor in the Execution Section.
FETCH the data from
cursor into PL/SQL variables or records in the Execution Section. CLOSE the cursor in the
Execution Section before you end the PL/SQL Block.
DECLARE
emp_rec emp_tbl%rowtype;
CURSOR emp_cur IS
SELECT *
FROM
WHERE salary > 10;
BEGIN
OPEN emp_cur;
FETCH emp_cur INTO emp_rec;
dbms_output.put_line (emp_rec.first_name || ' ' || emp_rec.last_name);
CLOSE emp_cur;
END;
Attributes
%FOUND
%NOTFOUND
%ISOPEN
%ROWCOUNT
SP STORED PROCECDURE
A stored procedure or in simple a proc is a named PL/SQL block which performs one or more specific
task.
Syntax
CREATE [OR REPLACE] PROCEDURE proc_name [list of parameters]
IS
Declaration section
BEGIN
Execution section
EXCEPTION
Exception section
END;
Example
CREATE OR REPLACE PROCEDURE employer_details
IS
CURSOR emp_cur IS
SELECT first_name, last_name, salary FROM emp_tbl;
emp_rec emp_cur%rowtype;
BEGIN
FOR emp_rec in sales_cur
LOOP
dbms_output.put_line(emp_cur.first_name || ' ' ||emp_cur.last_name
|| ' ' ||emp_cur.salary);
END LOOP;
END;
/

118

Execute a Procedure
Execute [or EXEC]Proc_name;
procedure_name;
in SQL>
Create Table Table-Name(Col1DataTypeNOTNULL,..PRIMARY KEY(COL1));
MODIFY
Alter table Table-Nameaddcolumn..
DELETE TABLE
Drop Table Table-Name
Index --> Index can speed execution of SQL With Condition
Create Index Index-Name on Table-Name (Column [order]) --> Asc(default)
--> Desc
Composite Index --> involves more than 1 column
Unique Index --> Prevent Duplication of Data
Clustered Index --> Sorted both Logically & Physically.
--> Created on Primary Key
Create index I1 on Employee (c1,c2); c1,c2 --> Columns in table Employee
Drop Index Index-Name;
Views -->namedTable,wontPhysicallySeparateDatadefineinterimofothertable
( base table )
Create View View-Name as Sub-Query
Can be used for multiple queries
Both Updatable & nonUpdatable
NULL --> Values desired
Insert into Table-Name[Column List ];
Update Table set Column =Update table-Name Where Condition;
Delete from Table-Name Condition;
Select Trunc(* ) from Table-Name --> Deletes the entire data leaves Table Structure alone.
Cast --> Scalar value to scalar Data-Type
Cast (scalar-exp) as { Data-Type }
CASE
When Cond-Exp then Scalar exp
Else
scalar Exp
end;
INDICATOR --> null indicator variable parameter sent to -1
SELECT --> Select ( all / Distinct) exp (Query) from Table-Name; Where Condition Group By
--> Usually refers for Aggregate functions / Columns
--> Having --> include certain Groups ,Equivalent to [ where ]
--> Order By --> Sort by Order --> Asc [default]
--> Desc [descending Order ]
Select Distinct (* ) from Table-Name --> Eliminate Duplicates
Select * from Table-Name where year in (1993,1996,1999);
--> check if it matches year values given
Select * from Table-Name where year not in (1993,1996,1999);

119
checkifitnotmatchesyearvaluesgiven.
Select * from Table-Name where C1 between [2 specific values ] Or Using Sub-Queries Correlated Sub
Query
--> execute Outer Query first , Sub-Query Next Usual
--> Sub Query Executed first then outer query .
Parallel Sub Query --> More than 1 sub query in a query.
Join
EQUI-JOIN --> comparison operator is equality
Non EQUI-JOIN--> comparison operator is not equal sign
Natural Join --> produce result that contain 2 identical rows ,1 row being Eliminated
Self Join --> A Table joined with Itself
Outer Join --> Extended Inner Join
Table are joined contain matching values both matching & non matching rows returned.
LEFT Outer Join --> Use Keyword LEFT [OUTER] or (*)
RIGHT Outer Join --> use keyword Right [OUTER]
FULL Outer Join --> use (+)
Grant Permission
Grant (All/Privilege)
On { Table Name Column-Name VIEW NAME }
To { PUBLIC /USER LIST }
With Grant option
Public --> to all users of the system
ALL --> all Privileges
With Grant --> All users can access Privileges
REVOKE --> Take away privileges given by Grant
Revoke { Privileges List / ALL }
On Table /Coloumn /View }
From { Public /User List }
I ntegrity Constraints --> restrict data values that can be inserted into database
that could be inserted into database that could be deleted & Modified.
Referential
Entity
Create Assertation check (not Exists (cond));
Domain
Create Domain D-Name as Defn
Alter Domain D-NameAdd../Drop
Candidate Key --> unique identifier ( a column or combination of columns) of table
Foreign Key --> a column or combination of column in one table ,values required to match
some candidate key in another table
Lock

--> On Reading Data


--> on Updating Data
Exclusive Lock --> during data modification on insert / delete / update
Update --> no access to other users
Shared Lock --> read only access to other users.
Trigger. --> An action database should take PL / SQL Code

120
--> Need to be executed only once and will get invoked automatically till dropped
Row Level Trigger --> once Fro each row of transaction
Statement Level Trigger --> Execute once for each transaction
Before Trigger , After Trigger
Create or Replace Trigger Trigger-Name
Before /After
Delete / INSERT / UPDATE
On [USER] Table-Name
For Each Row
[PL/SQL Block]
Backup:
COMMIT;
ROLLBACK;
SavePoint --> A point on transaction That you can rollback without rollback entire transaction.
SavePoint sp1
SQL1;
..
SavePoint sp2
SQL2;
Rollback sp2; --> rollback SP2
String DataTypes
CONCATINATION | | STRING | | STRING2
RPAD & LPAD --> Pad right side with any set of characters.
LTRIM --> delete unwanted character on left end of string.
RTRIM --> delete unwanted character on right end of string
Length (string) --> 6
SUBSTR(String, Start[count]); --> generate substring from start.
INSTR(String, Set[,start[ocandea]); --> insert a string at desired Location.
SOUNDEX --> Compare sound entry in selected coloumn
Dates
ADD_MONTHS (PDate ,2); PDATE --> Present date in Table
Least
Greatest
DUAL --> Inbuilt Table provides with 1 row & 1 column initialized by Oracle.
NEXT_DAY
LAST_DAY
MONTHS_BETWEEN
TO_DATE
ROUND
TRUNC
TO-CHAR
NEW-DATE
SYNONYM --> Alias Name to Object.
Create Synonym emp for emp1.employee select * from empl.employee --> replace emp in table name;
Drop Synonym emp;
SNAPSHOT --> Read Only Table
Simple SnapShot

121
Complex SnapShot
Create SnapShot emp;
EXECUTE Immediate --> Prepare / Execute Statement.
DECLARE --> Define a CURSOR
OPEN --> Define a executable statement
FETCH --> Return Data from Resultant Table
CLOSE --> Release all resources.
FUNCTION
A function is a named PL/SQL Block which is similar to a procedure. The major difference
between a procedure and a function is, a function must always return a value, but a procedure may or
may not return a value.
Syntax
CREATE [OR REPLACE] FUNCTION function_name [parameters]
RETURN return_datatype;
IS
Declaration_section
BEGIN
Execution_section
Return return_variable;
EXCEPTION
exception section
Return return_variable;
END;
PARAMETER PASSING
IN - We can pass values to the stored procedure through these parameters or variables. This type of
parameter is a read only parameter
OUT - The OUT parameters are used to send the OUTPUT from a procedure or a function
IN OUT - The IN OUT parameter allows us to pass values into a procedure and get output values from
the procedure. This parameter is used if the value of the IN parameter can be changed in the calling
program
DECLARE
empName varchar(20);
CURSOR id_cur SELECT id FROM emp_ids;
BEGIN
FOR emp_rec in id_cur
LOOP
emp_name(emp_rec.id, empName);
dbms_output.putline('The employee ' || empName || ' has id ' || emp-rec.id);
END LOOP;
END;
/
CREATE OR REPLACE PROCEDURE emp_salary_increase
(emp_id IN emptbl.empID%type, salary_inc IN OUT emptbl.salary%type)
IS

122
tmp_sal number;
BEGIN
SELECT salary
INTO tmp_sal
FROM emp_tbl
WHERE empID = emp_id;
IF tmp_sal between 10000 and 20000 THEN
salary_inout := tmp_sal * 1.2;
ELSIF tmp_sal between 20000 and 30000 THEN
salary_inout := tmp_sal * 1.3;
ELSIF tmp_sal > 30000 THEN
salary_inout := tmp_sal * 1.4;
END IF;
END;
/
The below PL/SQL block shows how to execute the above 'emp_salary_increase' procedure.
DECLARE
CURSOR updated_sal is
SELECT empID,salary
FROM emp_tbl;
pre_sal number;
BEGIN
FOR emp_rec IN updated_sal LOOP
pre_sal := emp_rec.salary;
emp_salary_increase(emp_rec.empID, emp_rec.salary);
dbms_output.put_line('The salary of ' || emp_rec.empID ||
' increased from '|| pre_sal || ' to '||emp_rec.salary);
END LOOP;
END;
/
PL/ SQL
JFile.java
A Java class that draws together various pieces of information about
operating system files and offers it through an API accessible from
PL/SQL.
Polishing up the delete method
public static int delete (String fileName)
{ File myFile = new File (fileName);
boolean retval = myFile.delete();
if (retval) return 1; else return 0; }
CREATE OR REPLACE FUNCTION fDelete ( file IN VARCHAR2)
RETURN NUMBER AS LANGUAGE JAVA
NAME
'JDelete.delete (java.lang.String)
return int';
IF fdelete
('c:\temp\temp.sql') = 1 THEN ...
FUNCTION fDelete (
file IN VARCHAR2) RETURN BOOLEAN;

123
/* Filename on companion disk: JFile.java * /
import java.io.File;
public class JFile {
public static int tVal ()
{ return 1; } ;
public static int fVal () { return 0; } ;
public static int delete (String fileName)
{ File myFile = new File (fileName);
boolean retval = myFile.delete();
if ( retval ) return tVal();
else return fVal();
}}
FUNCTION delete (file IN VARCHAR2) RETURN BOOLEAN;
END xfile;
So now we have the Boolean function specified. But how do we implement it? I have two
design objectives:
Hide the fact that I am relying on numeric values
to pass back TRUE or FALSE.Avoid hardcoding the 1 and 0 values in the package.To achieve
these objectives, I will define two global
variables in my package to hold the numeric values:
CREATE OR REPLACE PACKAGE BODY xfile IS
g_true INTEGER;
g_false INTEGER;
And way down at the end of the package body, I will create an initialization section that calls
these programs to initialize my globals. By taking this step in the initialization section, I avoid
unnecessary calls (and overhead) to Java methods:
BEGIN
g_true := tval;
g_false := fval;
END
xfile;
Back up in the declaration section of the package body, I will define two private functions,
whose only purpose is to give me access in my PL/SQL code to the JFile methods that have
encapsulated the 1 & 0:
FUNCTION tval RETURN NUMBER AS LANGUAGE JAVA
NAME 'JFile.tVal() return int';
FUNCTION fval RETURN NUMBER AS LANGUAGE JAVA
NAME 'JFile.fVal () return int';
I have now succeeded in soft-coding the TRUE/FALSE values in the JFile package. To enable the use of a
true Boolean function in the package specification, I create a private "internal delete" function that is a
wrapper for the JFile.delete( ) method. It returns a number:
FUNCTION Idelete (file IN VARCHAR2)
RETURN NUMBER AS LANGUAGE JAVA NAME 'JFile.delete
(java.lang.String) return int';
Finally, my public delete function can now call Idelete and convert the integer value to a Boolean
by checking against the global variable:
FUNCTION delete (file IN VARCHAR2) RETURN BOOLEAN AS

124
BEGIN
RETURN Idelete (file) = g_true;
EXCEPTION WHEN OTHERS THEN
RETURN FALSE;
END;
And that is how you convert a Java Boolean to a PL/SQL Boolean. You will see this same method
employed again and again in the xfile package body. One of my favorite features of JFile is its ability to
return a list of files found in a directory. It accomplishes this feat by calling the File.list( ) method; if the
string you used to construct a new File object is the name of a directory, it returns a String array of
filenames found in that directory. Let's see how I can make this information available in PL/SQL.
I create a String method called dirContents, as follows:
/* Filename on companion disk: JFile.java * /
public static String dirContents (String dir)
{
File myDir = new
File (dir);
String[] filesList = myDir.list();
String contents = new String();
for (int i = 0; i < filesList.length; i+ +)
contents = contents + listDelimiter + filesList[i];
return contents; }
This method instantiates a File object called myDir and then assigns the myDir.list( ) to a String array
called filesList. I then use a Java "for" loop to concatenate each of the files into a single String, separated
by the listDelimiter, and return that String. Over on the PL/SQL side of the world, I will create a wrapper
that calls this method:
FUNCTION dirContents (dir IN VARCHAR2)
RETURN VARCHAR2 AS LANGUAGE JAVA
NAME 'JFile.dirContents (java.lang.String)
return java.lang.String';
Self-joins can also be written as outer joins.
A stored procedure is a group of SQL statements that form a logical unit and perform a particular task.
Stored procedures are used to encapsulate a set of operations or queries to execute on a database
server. For example, operations on an employee database (hire, fire, promote, lookup) could be coded as
stored procedures executed by application code. Stored procedures can be compiled and executed with
different parameters and results, and they may have any combination of input, output, and input/output
parameters.
Stored procedures are supported by most DBMSs, but there is a fair amount of variation in their syntax
and capabilities. For this reason, we will show you a simple example of what a stored procedure looks like
and how it is invoked from JDBC, but this sample is not intended to be run.
MVC APPLICATION FLOW
General Project Flow

BROWSER

JSP

Servlets
(Controler)

B.O

DAO

DB

125
MODEL VIEW CONTROLLER ARCHITECTURE

MVC Architecure:
MVC 1 --> presentation Logic and Application Logic is combined together.
MVC 2 --> Presentation and Application logic is separated results in easy
maintenance and updates.
MVC1 Flow.

Servlet
User
Pwd
Submit

Reset
JSP(View)

Jdbc()
Set()
Get()

Actions Happens here


1. Populate New Form
2. Call Reset() method
3. Call set() and get()
4. store desired scope
5. Validate
6. Action As directed by Programmer.
STRUTS 1.2
--> a open Source F/W contain all kind of components.
--> to build web applications easily and quickly.
--> Apache Software Foundation Part of Jakarta Products
--> Based on MVC Design Pattern
--> Contains Approximately 250 Classes and Interfaces
Follow Front Controller Design pattern.
Model --> Database View --> Response from/to Browser Controller --> ActionServlet.
Basic Components --> Base F/W, JSTL, TILES Plug-in , Validator Plug-in
BASE FrameWork --> ActionServlet --> ControllerServlet.
Controller Components :
ActionServlet

--> Provided by F/W.


--> will populate class with data from the form.

DB

126
-->
-->
-->
-->

main controller class


receive all HTTP Requests
initializing struts framework
to be configured in web.xml.

RequestDespatcher --> Provided by F/W.


--> One Instance per application module processes all request per module
--> Invoke proper action Instance
--> Default implementation provided by F/W ( can exist if necessary )
Should always forward or redirect to a resource once it completes
STRUTS DATA FLOW
1) When a user submitted a jsp page. that page having (attribute of )action="login.do". the container will
call to WEB.XML. in that web.xml thert is two section servlet And servlet mapping
2) In servlet mapping it find *.do in the url-pattern. if it found to take the name of servlet. and check the
corresponding class. in the servlet section. that class is ActionServlet.
3) ActionServlet is the controller of Struts module architecture. in Action servlet having the service
method. in that method we create RequestPrecessor class instance
4) Service(req,res) RequestPrecessor rp = new RequestPrecessor();
5) We call a process method of RequestProcessor class through the instance rp.process(req,res)
6) In the request processor class have the process method with the parameter of req,res. then it has 1 if
condition in this class. that condition return always true. because that is dummy method.
7)Inside that condition ther is 6 steps are processing
a)Create a action mapping instance in the "Struts-Config.xml". it will kept all details of the action mapping
path, value, type forward, validation=true/false, input ="*.jsp" etc these r created instance
b)Then it will create Form class instance before it check the name of action mapping and form name are
coincidence or not if it same it will create form instance
c)Then it will go to ActionMapping instace the ris mention or not the validate =true/fale if false it will not
execute the this step else it will execute this step.
d) Then it will create action instance
e) Next it will take four parameters of execute Method it will return ActionErrors instance. if it is not
empty. it will go to error page other wise it will got to corresponding page. else if it is empty if will go
further and display corresponding value of page in jsp view.This is struts flow.
BASIC FLOW OF STRUTS
1. Container loads web.xml
2. It loads actionservlet and Struts-config.xml configured in Web.xml.
3. In HTML While submitting we use <action path ="/login" type = "LoginAction"> through
http://myhost/myapp/login.do . .do is configured in <url-pattern> as it should be directed to
ActionServlet .
4. Here we give 2 possibilities namely Success / Failure.
5. If Success the action tells the ActionServlet that the action has been successfully accomplished
or vice- versa.
6. The struts knows how to forward the specific page to the concerned destination. The model
which we want to use is entirely to you, the model is called from within the controller

127
components.
7. Action can also get associate with a JavaBean in our Struts configuration file. Java bean is
nothing but a class having getter and setter methods that can be used to communicate between
the view and the controller layer. These java beans are validated by invoking the validate()
method on the ActionForm by the help of the Struts system. The client sends the request by
the normal form submission by using Get or Post method, and the Struts system updates that
data in the Bean before calling the controller components.
8. The view we use in the struts can be either Jsp page, Velocity templates, XSLT pages etc. In
struts there are set of JSP tags which has been bundled with the struts distribution, but it is not
mandatory to use only Jsp tags, even plain HTML files can be used within our Struts application
but the disadvantage of using the html is that it can't take the full advantage of all the dynamic
features provided in the struts framework.
The framework includes a set of custom tag libraries that facilitate in creating the user interfaces
that can interact gracefully with ActionForm beans. The struts Jsp taglibs has a number of
generic and struts specific tags tags which helps you to use dynamic data in your view. These
tags helps us to interact with your controller without writing much java code inside your jsp.
These tags are used create forms, internally forward to other pages by interacting with the bean
and helps us to invoke other actions of the web application.
There are many tags provided to you in the struts frameworks which helps you in sending error
messages, internationalization etc.
Note: The points we have described above will be in effect if and only if when the ActionServlet is
handling the request. When the request is submitted to the container which call the ActionServlet, make
sure that the extension of the file which we want to access should have the extension .do.
Jakarta Struts Framework --> open source implementation of MVC (Model-View-Controller)pattern for
the development of web based applications.
ActionServlet--> The class org.apache.struts.action.ActionServlet is the called the
ActionServlet that plays the role of controller. All the requests to the server goes through the
controller. Controller is responsible for handling all the requests.
Extends javax.Servlet.HttpServlet
Receive all F/W requests
Select proper appropriate module
Delegate request handle to request processor Instance
One ActionServlet instance per <web-app>
Default implementation provided by F/W (can Exist if necessary)
Message Resources Definitions file Message Resources Definitions file are simple .properties
files and these files contains the messages that can be used in the struts project. Message
Resources Definitions files can be added to the struts-config.xml file through <message-resources /> tag.
<message-resourcesparameter=MessageResources/>
Action Class --> Need to be built by programmer.
--> The Action Class is part of the Model and is a wrapper around the business logic.
--> Action Class is to translate the HttpServletRequest to the business logic.
--> extends Action override ActionForwards execute() return type
--> Action Class all the database/business processing are done.
--> EJB classes are handled using Late Binding of ejb class
--> main controller class
--> receive all HTTP Requests
--> initializing struts framework

128
--> to be configured in web.xml.
Action Mapping --> select instance form --> the Action form bean for Request if any
REQ --> HTTPRequest for Processing
RES --> HTTPResponse for Processing
web.xml --> configure java web application properties of MiniHR app.
struts-config.xml --> configure struts fw.
ApplicationResources.properties. --> externalize app strings, labels without recompile.
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
public class TestAction extends Action {
public ActionForward execute( ActionMapping mapping, ActionForm form,
HttpServletRequest request,
HttpServletResponse response) throws Exception {
return mapping.findForward("testAction");
}
}
ActionForm --> JavaBean that extends org.apache.struts.action.ActionForm maintains the
session state for web application.
--> ActionForm object is automatically populated on the server side with data entered from
a form on the client side.
--> If ActionForm Declared as Interface possibility for MisMatch underlying business tier
instead of Strings, which violates one of the primary purposes for ActionForms in the first place (the
ability to reproduce invalid input, which is a fundamental user expectation).
ActionForms as an interface would also encourage using existing DAO objects as ActionForms by
adding implements ActionForm to the class. This violates the MVC design pattern goal of separation of
the view and business logic.
ActionForm
Public class abcform extends ActionForm {
// this is declared in form bean
}
public class abcAction extends Action {
//methods
public ActionForward execute(ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException {
Double price = null;
// Default target to success
String target = new String("success");
if ( form != null ) {
LookupForm lookupForm = (LookupForm)form;

129

String symbol = lookupForm.getSymbol();


price = getQuote(symbol);

// if price is null, set the target to failure


if ( price == null ) {
target = new String("failure");
}
else {
request.setAttribute("PRICE", price);
}
// Forward to the appropriate View
return (mapping.findForward(target));
}
}
DynaActionForms relieve developers of maintaining simple ActionForms.
--> Extends org.Apache.Struts.action.ActionForm
--> capture user Data from HttpServletRequest
--> store Data Temporarily
--> Acts as a Fire-Wall between Presentation and Application Layer
--> attributes /Arguments (Validation ,Reset)
--> ActionMapping , Request.
ActionForm
ActionForm is used, then user himself has to
write the setters and getters when ever he
adds a control same process is repeated again
and again when user creates a view

DYNAACTIONFORM
DynaActionForm eliminates this burden and
creates the form bean itself No bean class is
required for the DynaActionForm and we will
declare the form beans as DynaActionForm
type in struts-confing.xml. with its properties.

ActionForm generally contains user defined


validations on form fields

DynaActionForm doesn't contain validations on


form fields i.e., where form field validations are
not required there DyanActionForm is used
Validator Framework --> provides the functionality to validate the form data.
--> use to validate the data on the users browser as well as on the server side.
--> emits the java scripts and it can be used validate the form data on the client
browser.
--> Server side validation of form can be accomplished by sub classing your From
Bean with DynaValidatorForm
--> class get configured in validation.xml can be used for multiple operations.
validator-rules.xml --> defines standard validation routines, reusable and used in
validation.xml
--> error message key for validator tag.
--> specify javascript code
--> run on browser to perform client side validations
Validation.xml --> to define the form specific validations.
--> defines the validations applied to a form bean.
validation-key.xml --> specify a key stored in ApplicationResources.properties.
--> This key is same across each loacal properties file.
To use validator -->useActionFormsubclassesandimplementActionFormsvalidate();

130
<form-validation>
<formset>
<formname=>
<fieldproperty=depends=required></field></formset></form-validation>
<html:javascript formName=javascript>
Struts Validator

Strutsvalidatorframeworkprovidesanumberofbuilt-in validations for all normal business


requirements.
Thestrutsvalidator-rules.xml contains the name of the validation rule and the associated in built
method.
validation.xmlmapsyourformsfieldswithoneormorevalidationrules,specifiedinvalidatorrules.xml.
Your form bean should extend ValidatiorForm.
ApplicationResources.properties, the resource bundle for internationalization, maps the keys to the
respective values, for messages, labels, etc.,
The validator plugin should be included in struts-config.xml to enable the use of the validator frame
work by Struts controller.
Struts Controller invokes the validator plugin and ensures that all the specified fields are validated.
In addition to the above, if you want your validation to take into account values in more than one
field, then you may override the validate() method of the ValidatorForm class.
Extend ValidatorForm. In your formbean class.
(org.apache.struts.validator.ValidatorForm)
publicclassInputFormAllextendsValidatorForm{.}
The ValidatorForm , in fact is a subclass of ActionForm .
It overrides the Validate() method of the ActionForm.
Create your Action class which subclasses Action in the normal way.
publicclassInputActionAllextendsAction{..}
Create Resource Bundles with key / value pairs for the messages/
labels.(ApplicationResource.properties)
inputForm.userName=User name
inputForm.userName.mask={0} must start with a letter
.

validateSsnum() --> conforms proper method signature for custom validations.


--> perform actual validation logic.
Display validation fail errors on jsp page - < hml:errors> enable front-end validation
based on the xml in validation.xml. -->
< html:javascript> < html:javascript
formName=logonFormdynamicJavascript=truestaticJavascript=true/>
generatestheclientsidejavascriptfortheformlogonFormasdefinedinthevalidation.xmlfile.
Enable plugin in JSP use < plug-in> in struts-config.xml.
Struts Central collects and organizes links to all known Struts Resources, including articles,books, and
third-party extensions, for Action, Shale, and Action 2.
Reload removed from Struts (since 1.1) --> ReloadAction in Struts was trying to act like a container, but
it couldn't do a proper job of it.
--> It never did let you reload everything that you would really want to -particularly changed classes -- so many people ended up having to reload the webapp anyway.
--> Containers are starting to offer reload-on-demand features which does the same
thing as the Struts ReloadAction, only better.

131
--> Not supporting ReloadAction lets Struts avoid doing synchronization locks around all
the lookups (like figuring out which action to use, or the destination of an ActionForward) so applications
can run a little faster.
Action Servlet & Request Processor
Select Appropriate Module & handle it off to Request Process (Or)
Load in Struts (Or)
Request Comes in Servlet , Select Appropriate Module
Processing Done
1. Receive HttpServletRequest ( Handle Request )
2. Automatically populate a java bean from request parameter
3. Handle local and context type issues
4. Determine Action to invoke based URI provide extension Points
Form Bean
Form bean is part of view layer

Java Bean
Java-Bean is the part of model layer

MVC 2 Architecure Flow [ STRUTS]

Browser
WEB.XML
Struts-Config.xml
Action Servlet
Action Path

B.O

*.do
Action Class

ActionForward Execute()

Action Form

Set()
Get()

DAO
D.B

PRE-BUILT ACTION CLASSES IN STRUTS


1. public abstract class BaseAction extends org.apache.struts.action.Action ( BaseAction is
provided as an intermediate class for shared funtionality between Action and any stock
implementation provided in this package.
2. ForwardAction ( extends org.apache.struts.actions.BaseAction
Configure in Struts-config.xml
<action path="/saveSubscription" type="org.apache.struts.actions.ForwardAction"
name="subscriptionForm" scope="request" input="/subscription.jsp"

132
parameter="/path/to/processing/servlet"/>
( forward to specific URL)
3.DispatchAction ( extends BaseAction configure in struts-config.xml <action
path="/saveSubscription" type="org.apache.struts.actions.DispatchAction"
name="subscriptionForm" scope="request" input="/subscription.jsp" parameter="method"/>
public ActionForward delete(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) throws Exception
public ActionForward insert(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) throws Exception
public ActionForward update(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) throws Exception
The standard Struts development model requires a view, an ActionForm for that view and an Action
class, for every ActionForm.Your program should extend the DispatchAction class and provide
implementation for each of the required methods.
The values for the method parameter, passed by your view should bear the same name as that of the
respective method.
Create an action handler class which subclasses DispatchAction .
In that handler class, create the required methods to handle each of the actions.
Include an action mapping for this action handler using the parameter attribute in the struts-config.xml
file.
package com.abc.dispatchaction;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.actions.DispatchAction;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
public class UserDispatchAction extends DispatchAction {
public ActionForward save(ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException {
String user = null;
if ( form != null ) {
UserForm userForm = (UserForm)form;
user = userForm.getUser();
}
System.err.println("Saving user: " + user);
// Forward to the appropriate View
return (mapping.findForward("success"));
}
public ActionForward remove(ActionMapping mapping, ActionForm form,
HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException {

133
String user = null;
if ( form != null ) {
UserForm userForm = (UserForm)form;
user = userForm.getUser();
}
System.err.println("Removing user: " + user);
// Forward to the appropriate View
return (mapping.findForward("success"));
}

In DispatchAction, the Struts framework depended on the parameter values having the same name as
their associated actions.
But LookupDispatchAction implements a key-value relationship that does away with the naming
requirement of the DispatchAction.
Struts uses the key-value map to look up the corresponding method.
And it also uses a resource bundle for displaying label data and messages
4. DownloadAction ( protected abstract HYPERLINK "http://struts.apache.org/1.x/strutsextras/
apidocs/org/apache/struts/actions/DownloadAction.StreamInfo.html" \o "interface in
org.apache.struts.actions" DownloadAction.StreamInfo Methods
--> getStreamInfo(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) throws java.lang.Exception
protected int getBufferSize()--> Returns the size of the buffer to be used in transferring the
data to the servlet output stream. This method may be overridden by an extending class in
order to customize the buffer size.
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) throws java.lang.Exception
public int copy(InputStream input, OutputStream output)throws IOException --> Copy bytes
from an InputStream to an OutputStream.
5. public class IncludeAction extends BaseAction --> An Action that includes the contextrelative
URI specified by the parameter property of our associated ActionMapping. This can be used to integrate
Struts with other business logic components that are implemented as
servlets (or JSP pages), but still take advantage of the Struts controller servlet's functionality
(such as processing of form beans).
<action path= "/saveSubscription" type= "org.apache.struts.actions.IncludeAction"
name="subscriptionForm" scope= "request" input= "/subscription.jsp"
parameter="/path/to/processing/servlet">
--> execute() method
6. public final class LocaleAction extends BaseAction --> Implementation of Action that changes
the user's Locale and forwards to a page, based on request level parameters that are set (language,
country, & page).
--> execute()
-->convenientmechanismforsettinguserslocale.
--> create action mapping entry

134

7. public class SwitchAction extends BaseAction --> A standard Action that switches to a new
module and then forwards control to a URI (specified in a number of possible ways) within the new
module.
--> execute() method
--> switching between modules in modularized application
--> similar to ForwardAction.
8. public class EventDispatchAction extends DispatchAction --> An Action that dispatches to one
of the public methods that are named in the parameter attribute of the corresponding
ActionMapping and matches a submission parameter. This is useful for developers who prefer
to use many submit buttons, images, or submit links on a single form and whose related
actions exist in a single Action class.
<action path= "/saveSubscription"
type= "org.example.SubscriptionAction"
name= "subscriptionForm"
scope="request"
input="/subscription.jsp"
parameter="save,back,recalc=recalculate,default= save"/>
protected ActionForward unspecified(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) throws java.lang.Exception
protected String getMethodName(ActionMapping mapping, ActionForm form,
HttpServletRequest request,HttpServletResponse response, String parameter) throws
Exception
public abstract class LookupDispatchAction extends DispatchAction --> An abstract Action
that dispatches to the subclass mapped execute method. This is useful in cases where an
HTML form has multiple submit buttons with the same name. The button name is specified by the
parameter property of the corresponding ActionMapping. To configure the use of this
action in your struts-config.xml file, create an entry like this:
<action path= "/test" type= "org.example.MyAction" name= "MyForm" scope="request"
input="/test.jsp" parameter="method"/>
protected abstract Map getKeyMethodMap()
protected String getLookupMapName(HttpServletRequest request,
String keyName, ActionMapping mapping) throws ServletException
protected String getMethodName(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response,
String parameter) throws java.lang.Exception
--> extends DispatchAction
--> modularizing set of related functions into single action.
public class MappingDispatchAction extends DispatchAction --> An abstract Action that
dispatches to a public method that is named by the parameter attribute of the corresponding
ActionMapping. This is useful for developers who prefer to combine many related actions into a single
Action class.
<action path= "/saveSubscription"
type= "org.example.SubscriptionAction"
name= "subscriptionForm"
scope="request"
input="/subscription.jsp"
parameter="method"/>

135

public ActionForward create(ActionMapping mapping, ActionForm form,


HttpServletRequest request, HttpServletResponse response) throws Exception
public ActionForward edit(ActionMapping mapping, ActionForm form, HttpServletRequest
request, HttpServletResponse response) throws Exception
public ActionForward save(ActionMapping mapping, ActionForm form, HttpServletRequest
request, HttpServletResponse response) throws Exception
public ActionForward delete(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) throws Exception
public ActionForward list(ActionMapping mapping, ActionForm form, HttpServletRequest
request, HttpServletResponse response) throws Exception
For Internationalization we need lookupDispatchAction that holds a method named getMethodKey() to
find method based on method key.
A Dispatch Action calls the method based on Parameter Value where as in case of LookupDispatch Action
does a lookup to determine the method based on lookup.
A typical Execution flow for a Project in Struts
1. Userentersthecontexturlinthebrowsersaddressbar.
http://localhost:8084/Struts2
2. The welcome-file associated with the application is displayed.
index.jsp
3. User enters the data and clicks submit.
4. The<h:formaction>=tagappends.dototheactionnameandsubmitstheformtothe
server.
<html:form action="Lookup">
Lookup is the name of the action. It is changed to Lookup.do while being submitted to the
server.Thisisdonebythe<h:form/>element.
5. This .do extension is mapped to ActionServlet (Struts Controller Servlet) in the web.xml using
the action-mapping element.
<servlet>
<servlet-name>action</servlet-name>
<servlet-class>org.apache.struts.action.ActionServlet
</servlet-class>
.
</servlet>
<servlet-mapping>
<servlet-name>action</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
.
6.

Servlet Container now hands over control to ActionServlet along with the associated request,
response objects.
7. ActionServlet reads the struts-config.xml and finds out the Action form bean and Action class for
this url (action=Lookup)
<struts-config>
<form-beans>
<form-bean name="LookupForm" type="com.cts.test.LookupForm"/>

136
</form-beans>
<action-mappings>
<action
input="/index.jsp" name="LookupForm" path="/Lookup"
scope="session" type="com.xyz.test.LookupAction">
<forward name="success" path="/quote.jsp"/>
<forward name="failure" path="/index.jsp"/>
</action>
</action-mappings>
</struts-config>
8. It instantiates the Lookupform bean and populates it with request data.
9. If the bean instance is already present, it retrieves the instance and resets it with the request
data.
10. In a similar manner, the controller instantiates or retrieves an
instance of the Action Class, com.cts.test.LookupAction.
11. It then proceeds to create a mapping object, an instance of
ActionMapping , using the <action-mapping> details of the struts-config.xml.
12. As a next step, it invokes the execute() method of the Action class and passes the action form,
action mapping , request and response objects as arguments.
public ActionForward execute(ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response)
..
13. The execute method, which is the model component, performs the application logic as specified
in the code.
14. The execute method then returns an ActionForward object which specifies the next navigation
target.

return (mapping.findForward(target));
15. The Struts Controller Servlet (ActionServlet), uses this ActionForward object and invokes the
specified target view, which is determined from the <forward/>element of < action mapping/>.
<action-mappings>
<action

<forward name="success" path="/quote.jsp"/>


<forward name="failure" path="/index.jsp"/>
</action>
</action-mappings>
16. And, the cycle continues, if there happens to be more views in the application.
web.xml
<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE web-app
PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.2//EN"
"http://java.sun.com/j2ee/dtds/web-app_2_2.dtd">
<web-app>
<!-- Action Servlet Configuration -->
<servlet>
<servlet-name>action</servlet-name>
<servlet-class>org.apache.struts.action.ActionServlet</servlet-class>

137

<init-param>
<param-name>application</param-name>
<param-value>test.struts.MessageResources</param-value>
</init-param>
<init-param>
<param-name>mapping</param-name>
<param-value>org.apache.struts.action.RequestActionMapping</param-value>
</init-param>
<init-param>
<param-name>config</param-name>
<param-value>/WEB-INF/struts-config.xml</param-value>
</init-param>
<init-param>
<param-name>debug</param-name>
<param-value>2</param-value>
</init-param>
<load-on-startup>2</load-on-startup>
</servlet>
<!-- Action Servlet Mapping -->
<servlet-mapping>
<servlet-name>action</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
<!-- Struts Tag Library Descriptors -->
<taglib>
<taglib-uri>/WEB-INF/struts-bean.tld</taglib-uri>
<taglib-location>/WEB-INF/struts-bean.tld</taglib-location>
</taglib>
<taglib>
<taglib-uri>/WEB-INF/struts-html.tld</taglib-uri>
<taglib-location>/WEB-INF/struts-html.tld</taglib-location>
</taglib>
<taglib>
<taglib-uri>/WEB-INF/struts-logic.tld</taglib-uri>
<taglib-location>/WEB-INF/struts-logic.tld</taglib-location>
</taglib>
<taglib>
<taglib-uri>/WEB-INF/struts-template.tld</taglib-uri>
<taglib-location>/WEB-INF/struts-template.tld</taglib-location>
</taglib>
</web-app>
struts-config.xml
Contents
The top-level element is struts-config. Basically, it consists of the following elements:

138
data-sourcesA set of data-source elements, describing parameters needed to instantiate JDBC 2.0
Standard Extension DataSource objects
<data-sources>
<data-source autoCommit=false
description=SecondDatabaseConfig
driverClass=oracle.jdbc.driver.OracleDriver
key=REFDB
maxCount=4
minCount=2
password=admin
url=jdbc:oracle:thin:@localhost:1521/AUTHORDB
user=admin/>
</data-sources>
form-beansA set of form-bean elements that describe the form beans that this application uses
<form-beans>
<form-beanname=searchForm>
type=com.abc.struts.SearchForm
</form-bean>
</form-beans>
DynaActionForm Bean
The struts application design requires you to develop a ActionForm class, for every jsp page you display
for accepting user input.
Each of such ActionForm classes will have bean fields which represent the corresponding input fields.
In a multi-navigation struts application, this could be major effort which is avoidable.
Its here that the DyanaActionForm comes to our rescue.
In fact, DynaActionForm is a java class provided by the struts framework.
It should be configured in the struts-config.xml of your struts application along with the property (data
members) details.
Then the struts controller instantiates the actual form bean, using this configuration information.
And hence, there is NO need to develop individual form bean classes (ActionForm), corresponding to
each input jsp file.
<form-beans>
<form-bean name="dynamicLookupForm"
type="org.apache.struts.action.DynaActionForm">
<form-property name="symbol" type="java.lang.String"
</form-bean>
</form-beans>

initial="MSFT" />

There need to be one <form-property../> entry for every input field in your view.
In the Action Mapping, refer to the form using the name property in the usual way.

<action-mappings>
<action
path="/DynaLookup"
type="dya.DynaAction"
name="dynamicLookupForm"
input="/index.jsp">
<forward name="success" path="/quote.jsp"/>
<forward name="failure" path="/index.jsp"/>
</action>
</action-mappings>

139
DynaActionFom in Struts-Config.xml
<form-bean name="dynamicLookupForm"
type="org.apache.struts.action.DynaActionForm">
<form-property name="symbol" type="java.lang.String" initial="MSFT" />
</form-bean>
</form-beans>
global-forwardsA set of forward elements describing general available forward URIs
<global-forwards>
<forwardname=searchpath=/search.jsp/>
</global-forwards>
ActionMapping
This will be a boolean property.
The execute() method of your action class will inspect this attribute and display messages only if
true.
Implement the ActionForm class and Action class in the normal way as you do for any standard
struts application.
Define a class that extends org.apache.struts.action.ActionMapping
Provide a default public constructor, which invokes the super class default constructor.
Define the additional properties that you need to add as custom attributes.
Provide public setter and getter methods for these properties.
Include the className parameter in the action mapping elenment in the struts-config.xml file as
follows:
<action-mappings>
<action className="camap.CustomMapping"
path="/MapLookup"
type="camap.LookupAction"
name="lookupForm"
scope=request
validate=true
input="/index.jsp">
<set-property property="displayResults" value="true"/>
<forward name="success" path="/quote.jsp"/>
<forward name="failure" path="/index.jsp"/>
</action>
</action-mappings>
Struts Internationalization Set Property files in JSP
Application_Resources_en_US.properties ( for English,. US)
Application_Resources_it_IT.properties

(for Italian, Italy)

Include an entry in struts-config.xml after action mapping as follows:


<message-resources parameter="com/myapp/struts/ApplicationResources"/>
Sample Struts-Config.xml file
<?xml version= "1.0" encoding= "UTF-8"?>
<!DOCTYPE struts-config
PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 1.1//EN"
"http://jakarta.apache.org/struts/dtds/struts-config_1_2.dtd">

140
<struts-config>
<form-beans>
<form-bean name="loginForm" type="org.apache.struts.validator.DynaValidatorForm">
<form-property name= "password" type= "java.lang.String" />
<form-property name= "userName" type="java.lang.String" />
</form-bean>
</form-beans>
<global-exceptions>
</global-exceptions>
<global-forwards>
</global-forwards>
<action-mappings>
<action
attribute="loginForm"
input="/login.jsp"
name="loginForm"
path= "/login"
scope="request"
type= "project.struts.actions.LoginAction"
validate="true">
<forward name= "success" path="/index.jsp" redirect="true"/>
<forward name= "failure" path= "/login.jsp" redirect="true"/>
</action>
</action-mappings>
<controller
processorClass= "org.apache.struts.tiles.TilesRequestProcessor" maxFileSize= "250M"
bufferSize="4096" debug= "0" />
<message-resources parameter="struts" null="false" />
<plug-in className="org.apache.struts.tiles.TilesPlugin">
<set-property property="definitions-config"
value= "/WEB-INF/tiles-defs.xml" />
<set-property property="moduleAware" value="true" />
</plug-in>
<plug-in className="org.apache.struts.validator.ValidatorPlugIn">
<set-property property="pathnames"
value= "/WEB-INF/validator-rules.xml,/WEB-INF/validation.xml" />
</plug-in>
</struts-config>
Reg Redirect in Struts
ActionRedirect redirect = new ActionRedirect(mapping.findForward("fwd.send"));
redirect.addParameter("dispatch", "rev");
redirect.addParameter("commonInt", Integer.parseInt(request.getParameter("commonInt")));
return redirect;
<global-forwards>
<forward name="toModuleB" contextRelative="true" path="/moduleB/index.do"
redirect="true"/>
By default its false
...
</global-forwards>

141

Struts-Config.xml for email validation


<form-beans>
<form-bean name="userForm" type="org.apache.struts.validator.DynaValidatorForm">
<form-property name="dob" type="java.lang.String" />
<form-property name="emailId" type="java.lang.String" />
</form-bean>
</form-beans>
Validation.xml
<form name="userForm">
<field property="dob" depends="required,date">
<arg key="userForm.dob"/>
<var>
<var-name>datePattern</var-name>
<var-value>MM-dd-yy</var-value>
</var>
</field>
<field property="emailId" depends="required,email">
<arg key="userForm.emailId"/>
</field>
</form>
To ADD HIBERNATE IN STRUTS
<plug-in className="edu.arbor.util.plugin.HibernatePlugIn">
<set-property property="configFilePath" value="path-to-config-file" />
<set-property property="storeInServletContext" value="true-or-false" />
</plug-in>
<!path-to-config-file' is relative to the root of the class path. It MUST start with a '/'. The default is
"/hibernate.cfg.xml" -->
Call Spring in Struts
<plug-in
className="org.springframework.web.struts.ContextLoaderPlugIn">
</plug-in>
<action-mappings>
<action
path="/widgetListAction"
type="org.springframework.web.struts.DelegatingActionProxy"
scope="request">
</action>
</action-mappings>
For tiles in web.xml
<taglib>
<taglib-uri>/tags/struts-tiles</taglib-uri>
<taglib-location>/WEB-INF/struts-tiles.tld</taglib-location>
</taglib>

142
validation.xml
<?xml version= "1.0" encoding= "UTF-8"?>
<!DOCTYPE form-validation PUBLIC
"-//Apache Software Foundation//DTD Commons Validator Rules Configuration
1.1.3//EN"
"http://jakarta.apache.org/commons/dtds/validator_1_1_3.dtd">
<form-validation>
<formset>
<form name= "loginForm">
<field property="userName" depends="required">
<arg0 name="required" key="loginForm.userName"/>
</field>
<field property="password" depends="required">
<arg0 name="required" key="loginForm.password"/>
</field>
</form> </formset>
</form-validation>
Model --> External Interface --> Business Logic --> Data Access.
Form-beans ( life cycle) --> Controller servlet --> retrieve form Bean--> store Form Bean
--> reset() --> populate form Bean with data --> validate()--> (errors) --> input page
--> (no errors) --> execute() in action execute() --> similar to doGet() or doPost() method in Servlets.
Control layer (Life Cycle) --> Browser --> ActionServlet --> RequestProcessor --> Action --> Model /
View. ( View Previously given the Brief Picture ) Action class --> provide bridge between view and Model.
MappingDispatchAction --> subclass of DispatchAction
--> modularizing set of related functions into single action.
ActionForward --> Encapsulates Forward.
Validator plugin--> each is a java method plugged into system to perform specific validation.
validator-rules.xml --> declarative plugin to check validation process.Default validations.
byte , creditCard ,date , double, email , float , floatRange, integer , intRange, long,
mask , maxlength, minlength , range ,required , requireddif, short.
Tiles tag library

-->

used for formatting pages

< tiles:initComponentDefinitions> --> insert , put, putList , useAttribute.eg.


<tiles:putname=<%=title%>-title/>
< tiles:add> --> define a entry for list created by putList tag
beanName , beanProperty, beanscope , content ,direct , role ,type, value.
< tiles:definition> --> define a tile, store in jsp scriplet var.extends , id ,page ,role , scope, template.
< tiles:getAsString> --> render value of tiles attribute ignore ,name , role.
< tiles:importAttribute> --> store value a of all defined tiles attributes in jsp script.
ignore ,name ,scope
< tiles:initComponentDefinitons> --> init tiles defn factory into xml config file
classname , file
< tiles:insert> --> insert a tiles definition into JSP page
--> attribute ,beanName , beanProperty, beanScope, component
,controllerClass, --> controllerUrl, definition, flush, ignore, name, page, role, template.
< tiles:put> --> define attributes for a definition specify name and values
--> beanName, beanProperty, beanScope ,content ,direct , name ,role, type, value.

143

< tiles:putList> --> define (java.util)list attributecontain an ordered coll of indv attrib name
< tiles:useAttribute> --> to store value of tiles attribute in jsp scripting variable
--> classname , id ,ignore ,name ,scope ,
Exception: --> override org.apache.struts.action.ExceptionHandler.sexecute().
define in struts-config.xml.
custom exception handler --> create new exception handler class
--> add new exception handler class into struts-config.xml file
<exceptiontype=NoResultsFoundExceptionhandler=EmailExceptionHandler
key=error.NoResultsFoundExceptionpath=/exception.jsp>
Exception thrown : javax.servlet.ServletException: BeanUtils.populate
This error occurs as Struts is trying to populate the properties in your ActionForm from
the data entered into an HTML form. It means that Struts is unable to convert the String that is coming
from the HTML form into whatever data type you specified for a property in your ActionForm.
Bean Tag Library
<taglib>
<taglib-uri> </taglib-uri> --> declare URI
<taglib-location> <taglib-location> --> actual loc of taglib desc .tld. </taglib>
Bean Library Tags
<bean:cookie id name value /> --> store ref of HTTP cookie
<bean:define id name/> --> store ref of existing obj in jsp script var
<bean:header id name value/> --> store reference of HTTP header from incoming request.
<bean:include id forward> --> perform request to page,store content as string in jsp with
scope as page.
<bean:message key /> --> to retrieve an internationalized msg from struts
ApplicationResources.properties to JSP outputstream
<bean:page id property/> --> store one of implicit objects with scope page.
--> (implicit obj application, config, request, response, session)
<bean:parameter id name value/> --> store para from incoming req,store page scope
<bean:resource id name/> --> load contents of webapp resource and store as String obj.
<bean:size id collection/> --> store the size of an array.based on util.map,etc
<struts-config> --> store ref to struts config obj in JSP with scope page
--> access to config objects
FormBeanConfig, ForwardConfig, ActionConfig
<bean:write> --> to render value of an object into jsp output stream

144
All Html Tags are used with < html: tagname>
Logic Tag Library.
<logic:empty name property> --> conditionally processed specified obj is null or not.
<logic:equal cookie header value> --> conditionally processed specified object holds
specified constant value.
<logic: forward name/> --> looks fwd from struts config file redirects to it.
<logic: greaterEqual cookie value> --> like equal tag check if value is gt or equal.
<logic:greaterThan cookie value> --> similar to equal,check gt constant value.
--> works for both numeric and string compares.
<logic:iterate id collection> --> wrap content of repeated element in collection.
<logic: lessEqual cookie value> --> like equal tag check if value is lt or equal.
<logic:match cookie value> --> check object value starts with / ends with specific const.
<logic:messageNotPresent>--> check org.apache.struts.action.ActionErrors for errors
--> optionally specify particular property check for error.
--> check if no errors are present
<logic:messagePresent>

--> similar to messageNotPresent tag.


--> check if any errors are present

<logic:notEqual> --> check object value not equal to a const value.


<logic:notMatch cookie value> --> not a specific object value it contain similar to match.
<logic:notPresent header> --> check whether a specific object exists or not.
<logic:present cookie> --> similar to notPresent,check whether object exists.
<logic:redirect href> --> redirects to another URL.
Nested Tag Library
< nested:nest property> --> all logical level of nesting hierarchy.object with all nested tags.
--> number of tags available includes checkbox radiobutton etc.
<nested:root> --> define root object of nested hierarchy of objects.
<nested: writeNesting property> --> render and create jsp scripting variable.
JSTL with struts --> refer JSP Tag Library given before.
modular application - module-relative. --> Since Struts 1.1, the framework supports multiple
application modules. All applications have at least one root, or default, module. Like the root directory in
a file system, the default application has no name. (Or is named with an empty string, depending your
viewpoint.) Developing an application with only a default module is no different from how applications
were developed under Struts 1.0. Since Struts 1.1, you can add additional modules to your application,
each of which can have their own configuration files,messages resources, and so forth. Each module is

145
developed in the same way as the default module. Applications that were developed as a single module
can added to a multiple module application, and modules can promoted to a standalone application
without change.
A modular application is a Struts application that uses more than one module. Module-relative means that
the URI starts at the module level,rather than at the context level, or the absolute-URL level.
Absolute URL: http://localhost/myApplication/myModule/myAction.do
context-relative: /myModule/myAction.do
module-relative: /myAction.do
Since the goal of struts is to enforce this separation, it just makes more sense for Struts to own the
ActionForm.
ActionForms have to be true JavaBeans --> The utilities that Struts uses (Commons-BeanUtils since
1.1) require that ActionForm properties follow the JavaBean patterns for mutators and accessors (get*
,set* ,is* ). Since Struts uses the Introspection API with the ActionForms, some containers may require
that all the JavaBean patterns be followed, including declaring
"implements Serializable" for each subclass. Since Struts 1.1, you can also use DynaActionForms and
mapped-backed forms, which are not true JavaBeans. multiple HTML form element is defined by define a
element as an array and Struts will
autopopulate it like any other.
private String[] id= { } ;
public String[] getId() { return this.id; }
public void setItem(String id[]) { this.id = id;}
multiple submit buttons on the same form --> Yes. The issue is that only one action class can be
associated with a single form. So the real issue is how do I decode multiple submit types to a single
Action class. There is more than one way to achieve this functionality. Use You can roll your own with
JavaScript events and javascript:void
(document.forms["myform"].submit) on any html element. This gives you control of how you want your
page to look. Again you will have to decode the expected action in the execute method of your action
form if you choose this route.
<html:form> --> Unfortunately, there is some disagreement between the various browsers,and
different versions of the same browser, as to how the focus can be set. The <html:form> tag provides a
quick and easy JavaScript that will set the focus on a form for most versions of most browsers. If this
feature doesn't work for you, then you should set the focus using your own JavaScript. The focus feature
is a convenient "value-add" -- not a core requirement of the tag. If you do come up with a JavaScript that
provides the final solution to this project, please post your patch to this Bugzilla ticket.
checkboxes not being set from ON to OFF --> A problem with a checkbox is that the browser will only
include it in the request when it is checked. If it is not checked, the HTML specification suggests that it
not be sent (i.e. omitted from the request). If the value of the checkbox is being persisted, either in a
session bean or in the model, a checked box can never unchecked by a HTML form -- because the form
can never send a signal to uncheck the box. The application must somehow ascertain that since the
element was not sent that the
corresponding value is unchecked.
The recommended approach for Struts applications is to use the reset method in the
ActionForm to set all properties represented by checkboxes to null or false. The checked
boxes submitted by the form will then set those properties to true. The omitted properties
will remain false. Another solution is to use radio buttons instead, which always submit a
value.
It is important to note that the HTML specification recommends this same behavior whenever a control is
not "successful". Any blank element in a HTML form is not guaranteed to submitted. It is therefor very

146
important to set the default values for an ActionForm correctly,and to implement the reset method when
the ActionForm might kept in session scope.
JavaScript to submit a form --> use < html:form>
<a href='javascript:void(document.forms["myForm"].submit()>My Link</a>
<input type='hidden' value='myAction' />
<input type='button' value='Save Meeeee'
onclick='document.forms[ "myForm"].myAction.value="save";
document.forms["myForm"].submit();' />
<input type='button' value='Delete Meeeee'
onclick='document.forms[ "myForm"].myAction.value="delete";
document.forms["myForm"].submit();' />
... the java part ...
class MyAction extends ActionForm implements Serializable {
public ActionForward execute (ActionMapping map, ActionForm form,
HttpServletRequest req, HttpServletResponse) {
String myAction = req.getParameter("myAction");
if (myAction.equals("save") {
// ... save action ...
} else if (myAction.equals("delete") {
// ... delete action ...
}}}}
This is just one of many ways to achieve submitting a form and decoding the intended action.
Once you get used to the framework you will find other ways that make more sense for your
coding style and requirements. Just remember this example is completely non-functional
without JavaScript.
To use JavaScript to --> Struts is mainly a server-side technology. We bundled in some JSP
tags to expose the framework components to your presentation page, but past that, the
usual development process applies.
Interactive pages require the use of JavaScript. You use JavaScript with Struts the same way you use
with any presentation page. Since JavaScript is a client-side technology, you can use simple relative
references to your scripts. If you need to fire a JavaScript from a HTML control, the Struts HTML tags
have properties for the JavaScript events.
Is need to implement reset and set all my form properties to their initial values --> No.
You need to set checkbox properties to false if the ActionForm is being retained in session scope. This is
because an unchecked box does not submit an attribute. Only checked boxes submit attributes. If the
form is in session scope, and the checkbox was checked, there is no way to turn it back off without the
reset method. Resetting the properties for other controls, or for a
request scope form, is pointless. If the form is in request scope, everything already just
started at the initial value.
create JavaBeans in the JSP using a scriptlet --> yes.you can do all with respect to MVC1
Use other beans or hashmaps with ActionForms --> ActionForms can have other beansor
hashmaps as properties "Value Beans" or "Data Transfer Objects" (DTOs) can be used
independently of ActionForms to transfer data to the view .ActionForms can use Maps to
support "dynamic" properties (since Struts 1.1)

147
ActionForms are really just Java beans (with a few special methods) that Struts creates and
puts into session or request scope for you. There is nothing preventing you from using other beans, or
including them in your form beans. Here are some examples:
Collections as properties Suppose that you need to display a pulldown list of available colors on an input
form in your application. You can include a string-valued colorSelected property in your ActionForm to
represent the user's selection and a colorOptions property implemented as a Collection (of strings) to
store the available color choices. Assuming that you have defined the getters and setters for the
colorSelected and colorOptions properties in your orderEntryForm form bean, you can render the
pulldown list using:
<html:select property= "colorSelected">
<html:options property="colorOptions" name= "orderEntryForm"/>
</html:select>
The list will be populated using the strings in the colorOptions collection of the orderEntryForm and the
value that the user selects will go into the colorSelected property that gets posted to the subsequent
Action. Note that we are assuming here that the colorOptions property of the orderEntryForm has already
been set.
Independent DTO An Action that retrieves a list of open orders (as an ArrayList of Order objects) can
use a DTO independently of any form bean to transfer search results to the view. First, the Action's
execute method performs the search and puts the DTO into the request:
ArrayList results = businessObject.executeSearch(searchParameters);
request.setAttribute("searchResults",results);
Then the view can iterate through the results using the "searchResults" request key to
reference the DTO: `
<logic:iterate id= "order" name="searchResults" type="com.foo.bar.Order">
<tr> <td><bean:write name="order" property="orderNumber"/> <td>
<td> ..other properties...</td> </tr>
</logic:iterate>
Struts tags provide for so little formatting --> The Struts tags seem to provide only the most
rudimentary functionality. Why is there not better support for date formatting and advanced string
handling?
First, work started on the JSTL and we didn't want to duplicate the effort.
Second, work started on Java Server Faces, and we didn't want to duplicate that effort either.
Third, in a Model 2 application, most of the formatting can be handled in the ActionForms (or in the
business tier), so all the tag has to do is spit out a string. This leads to better reuse since the same "how
to format" code does not need to be repeated in every instance. You can "say it once" in a JavaBean and
be done with it.
Struts taglibs offer more layout options --> Since the Struts tags are open source, you can extend them
to provide whatever additional formatting you may need. <html:link> tag URLencode
javascript and mailto links --> The <html:link> tag is not intended for use with clientside references
like those used to launch Javascripts or email clients. The purpose of link tag is to interject the context
(or module) path into the URI so that your server-side links are not dependent on your context (or
module) name. It also encodes the link, as needed, to maintain the client's session on the server. Neither
feature applies to client-side links, so there is no reason to use the <html:link> tag. Simply markup the
client-side links using the standard tag.

148

option tag render selected=selected instead of just selected --> Attribute minimization (that is,specifying
an attribute with no value) is a place where HTML violates standard XML syntax rules. This matters a lot
for people writing to browsers that support XHTML, where doing so makes the page invalid.It's much
better for Struts to use the expanded syntax, which works the same on existing browsers interpreting
HTML, and newer browsers that expect XHTMLcompliant
syntax. Struts is following the behavior recommended by the XHTML specification
Part of Struts --> JavaServer Pages, HTML pages, WML files, Java servlets, Velocity
templates, and XML/XLST
ActionForms have to be true JavaBeans --> ActionForms are added to a servlet scope (session or
request) as beans.
First, your ActionForm bean must have a zero-arguments constructor. This is required because Struts
must be able to dynamically create new instances of your form bean class, while knowing only the class
name. This is not an onerous restriction, however, because Struts will also populate your form bean's
properties (from the request parameters) for you. Second, the fields of your form bean are made
available to the framework by supplying public getter and setter methods that follow the naming design
patterns described in the JavaBeans Specification. For most users, that means using the following idiom
for each of your form bean's properties:
private { type} fieldName;
public { type} getFieldName() { return (this.fieldName); }
public void setFieldName({ type} fieldName) { this.fieldName = fieldName; }
NOTE - you MUST obey the capitalization conventions shown above for your ActionForm properties to be
recognized. The property name in this example is "fieldName", and that must also be the name of the
input field that corresponds to this property. A bean property may have a "getter" method and a "setter"
method (in a form bean, it is typical to have both) whose name starts with "get" or "set", followed by the
property name with the first character capitalized. (For boolean properties, it is also legal to use "is"
instead of "get" as the prefix for the getter method.)
Advanced JavaBeans users will know that you can tell the system you want to use different names for the
getter and setter methods, by using a java.beans.BeanInfo class associated with your form bean.
Normally, however, it is much more convenient to follow the standard conventions.
WARNING - developers might be tempted to use one of the following techniques, but any of them will
cause your property not to be recognized by the JavaBeans introspection facilities,and therefore cause
your applications to misbehave:
Using getter and setter method names that do not match - if you have a getFoo() method for your
getter, but a setBar() method for your setter, Java will not recognize these methods as referring to the
same property. Instead, the language will think you have a read-only property named "foo" and a writeonly property named "bar".
Using more than one setter method with the same name - The Java language lets you "overload"
methods, as long as the argument types are different. For example, you could have a
setStartDate(java.util.Date date) method and a setStartDate(String date) method in the same class, and
the compiled code would know which method to call based on the parameter type being passed.
However, doing this for form bean properties will prevent Java from recognizing that you have a
"startDate" property at all.
I have to have a separate ActionForm bean for every HTML form --> it is a good practice to create a new
ActionForm for each action sequence. You can use DynaActionForms to help reduce the effort required,
or use the code generation facilities of your IDE.
Some issues to keep in mind regarding reuse of form beans are as follows:

149
Validation - You might need to use different validation rules depending upon the action that is currently
being executed.
Persistence - Be careful that a form populated in one action is not unexpectedly reused in a different
action. Multiple <form-bean> entries in struts-config.xml for the same ActionForm subclass can help
(especially if you store your form beans in session scope). Alternatively, storing form beans in request
scope can avoid unexpected interactions (as well as reduce the memory footprint of your application,
because no server-side objects will need to be saved in between requests.
Checkboxes - If you do as recommended and reset your boolean properties (for fields presented as
checkboxes), and the page you are currently displaying does not have a checkbox for every boolean
property on the form bean, the undisplayed boolean properties will always appear to have a false value.
Workflow - The most common need for form bean reuse is workflow. Out of the box, Struts has limited
support for workflow, but a common pattern is to use a single form bean with all of the properties for all
of the pages of a workflow. You will need a good understanding of the environment (ActionForms,
Actions, etc.) prior to being able to put together a smooth workflow environment using a single form
bean.
As you get more comfortable, there are a few shortcuts you can take in order to reuse your ActionForm
beans. Most of these shortcuts depend on how you have chosen to implement your Action / ActionForm
combinations.
Prepopulate a form --> The simplest way to prepopulate a form is to have an Action whosesole purpose
is to populate an ActionForm and forward to the servlet or JSP to render that form back to the client. A
separate Action would then be use to process the submitted form fields, by declaring an instance of the
same form bean name.
The struts-example example application that is shipped with Struts illustrates this design
pattern nicely. Note the following definitions from the struts-config.xml file:
...
< form-beans>
...
<-- Registration form bean -->
< form-bean name="registrationForm"
type="org.apache.struts.webapp.example.RegistrationForm"/>
...
</form-beans>
...
<action-mappings>
...
<-- Edit user registration -->
<action path="/editRegistration"
type="org.apache.struts.webapp.example.EditRegistrationAction"
name="registrationForm"
scope= "request"
validate= "false"/>
...
<-- Save user registration -->
<action path="/saveRegistration"
type="org.apache.struts.webapp.example.SaveRegistrationAction"
name="registrationForm"
input= "registration"
scope= "request"/>
...</action-mappings>
Both the /editRegistration and /saveRegistration actions use the same form bean.
When the /editRegistration action is entered, Struts will have pre-created an empty form

150
bean instance, and passed it to the execute() method. The setup action is free to preconfigure the values
that will be displayed when the form is rendered, simply by setting the corresponding form bean
properties.
When the setup action completes configuring the properties of the form bean, it should
return an ActionForm that points at the page which will display this form. If you are using the Struts JSP
tag library, the action attribute on your <html:form> tag will be set to /saveRegistration in order for
the form to be submitted to the processing action.
Note that the setup action (/editRegistration) turns off validation on the form that is being setup. You will
normally want to include this attribute in the configuration of your setup actions, because you are not
planning to actually process the results -- you simply want to take advantageof the fact that Struts will
precreate a form bean instance of the correct class for you.
The processing action (/saveRegistration), on the other hand, leaves out the validate attribute,which
defaults to true. This tells Struts to perform the validations associated with this form bean before
invoking the processing action at all. If any validation errors have occurred, Struts will forward back to
your input page (technically, it forwards back to an ActionForward named "registration" in this case,
because the example webapp uses the inputForward attribute in the<controller> element -- see the
documentation describing struts-config.xml for more information) instead of calling your processing
action.
Can I have an Action without a form --> Yes. If your Action does not need any data and it does not
need to make any data available to the view or controller component that it forwards to,it doesn't need a
form. A good example of an Action with no ActionForm is the LogoffAction in the struts example
application:
<action path= "/logoff"
type= "org.apache.struts.webapp.example.LogoffAction">
<forward name= "success" path="/index.jsp"/>
</action>
This action needs no data other than the user's session, which it can get from the Request, and it doesn't
need to prepare any view elements for display, so it does not need a form. you cannot use the <
html:form> tag without an ActionForm. Even if you want to use the <html:form> tag with a simple
Action that does not require input, the tag will expect you to use some type of ActionForm, even if it is an
empty subclass without any properties.
Validation Format
<form name= "medicalStatusForm">
<field property="pregnancyTest" depends="validwhen">
<arg0 key="medicalStatusForm.pregnancyTest.label"/>
<var>
<var-name>test</var-name>
<var-value>((((sex = = 'm') OR (sex == 'M')) AND (* this* = = null)) OR (* this* !=
null))</test></var></field>
Let's assume you have a medical information form with three fields, sex, pregnancyTest, and testResult.
If sex is 'f' or 'F', pregnancyTest is required. If pregnancyTest is not blank, testResult is required. The
entry in your validation.xml file would look like this:
<form name= "medicalStatusForm">
<field property="pregnancyTest" depends="requiredif">
<arg0 key="medicalStatusForm.pregnancyTest.label"/>
<var><var-name> field[0]</var-name>
<var-value>sex</var-value></var>
<var>
<var-name> fieldTest[0]</var-name>
<var-value>EQUAL</var-value>
</var>

151

<var>
<var-name> fieldValue[0]</var-name>
<var-value>F</var-value>
</var>
<var>
<var-name> field[1]</var-name>
<var-value>sex</var-value>
</var>
<var>
<var-name> fieldTest[1]</var-name>
<var-value>EQUAL</var-value>
</var>
<var>
<var-name> fieldValue[1]</var-name>
<var-value>f</var-value>
</var>
<var>
<var-name> fieldJoin</var-name>
<var-value>OR</var-value>
</var>
</field>
<field property="testResult" depends= "requiredif">
<arg0 key="medicalStatusForm.testResult.label"/>
<var>
<var-name> field[0]</var-name>
<var-value>pregnancyTest</var-value>
</var>
<var>
<var-name> fieldTest[0]</var-name>
<var-value>NOTNULL</var-value>
</var>
</field>
</form>
Best time to validate input --> This is an excellent question. Let's step back a second and think about
a typical mid to large size application. If we start from the back end and work toward the view we have:
1) Database: Most modern databases are going to validate for required fields, duplicate
records, security constraints, etc.
2) Business Logic: Here you are going to check for valid data relationships and things that make sense
for the particular problem you are triing to solve.
... This is where struts comes into the picture, by now the system should be pretty well
bulletproof. What we are going to do is make validation friendlier and informative. Rember it
is OK to have duplicate validations...
3) ActionErrors validate(ActionMapping map, HttpServletRequest req) is where you can do your
validation and feed back to the view, information required to correct any errors. Validate is run after the

152
form has been reset and after the ActionForm properties have been set from corresponding view based
input. Also remember you can turn validation off with validate="false" in the action mapping in the
struts-config.xml. This is done by returning anActionErrors collection with messages from your
ApplicationResources.properties file.The <html:error> tag allows you to dump all errors on your page
or a particular error
associated with a particular property. The input attribute of the struts-config.xml action
allows you to send validation errors to a particular jsp / html / tile page.
4) You can have the system perform low level validations and client side feedback using a ValidatorForm
or its derivatives. This will generate javascript and give instant feedback to the user for simple data entry
errors. You code your validations in the validator-rules.xml file. A working knowledge of regular
expressions is necessary to use this feature effectively. For more information, see User Guide
After Struts 1.1 ActionErrors are replaced with ActionMessages.
In JSP
<logic:messagesPresent>
<html:messages id="message1" property="noRecordFound" bundle="wag">
<bean:write name="message1" />
</html:messages>
</logic:messagesPresent>
In Action class , in method ActionForward Process()
ActionErrors errors = new ActionErrors();
errors.add( "noRecordFound", new ActionError( "No Record Found" ) );
saveErrors( request, errors );
In Validation-rules.xml
view plaincopy to clipboardprint?
<validator name="requiredif"
classname="org.apache.struts.validator.FieldChecks"
method="validateRequiredIf"
methodParams="java.lang.Object,
org.apache.commons.validator.ValidatorAction,
org.apache.commons.validator.Field,
org.apache.struts.action.ActionErrors,
org.apache.commons.validator.Validator,
javax.servlet.http.HttpServletRequest"
msg="errors.required">
</validator>
Using ActionMessages
In JSP
<logic:messagesPresent>
<html:messages id="message1" property="noRecordFound" bundle="wag">
<bean:write name="message1" />
</html:messages> </logic:messagesPresent>
In Action Class
ActionMessages messages= new ActionMessages();
messages.add( "noRecordFound", new ActionMessage( "No Record Found" ) );
saveMessages( request, messages
validation-rules.xml
<validator name="requiredif"
classname="org.apache.struts.validator.FieldChecks"
method="validateRequiredIf"

153
methodParams="java.lang.Object,
org.apache.commons.validator.ValidatorAction,
org.apache.commons.validator.Field,
org.apache.struts.action.ActionMessages,
org.apache.commons.validator.Validator,
javax.servlet.http.HttpServletRequest"
msg="errors.required">
</validator>
I avoid validating a form before data is entered --> The simplest way is to have two actions. The
first one has the job of setting the form data, i.e. a blank registration screen. The second action in our
writes the registration data to the database. Struts would take care of invoking the validation and
returning the user to the correct screen if validation was not complete.
The EditRegistration action in the struts example application illustrates this:
<action path="/editRegistration"
type= "org.apache.struts.webapp.example.EditRegistrationAction"
attribute="registrationForm"
scope="request"
validate="false">
< forward name= "success path="/registration.jsp"/>
</action>
When the /editRegistration action is invoked, a registrationForm is created and added to therequest, but
its validate method is not called. The default value of the validate attribute istrue, so if you do not want
an action to trigger form validation, you need to remember to add this attribute and set it to false.
create a wizard workflow --> The basic idea is a series of actions with next, back, cancel and finish
actions with a common bean. Using a LookupDispatchAction is reccomended as it fits the design pattern
well and can be internationalized easily. Since the bean is shared, each choice made will add data to the
wizards base of information.
A sample of struts-config.xml follows:
< form-beans>
< form-bean name= "MyWizard" type="forms.MyWizard" /> </ form-beans>
<!-- the first screen of the wizard (next action only available) -->
<!-- no validation, since the finish action is not available -->
<actions>
<action path="/mywizard1" type="actions.MyWizard" name="MyWizard"
validate="false" input="/WEB-INF/ jsp/mywizard1.jsp">
<forward name="next" path="/WEB-INF/ jsp/mywizard2.jsp" />
<forward name="cancel" path="/WEB-INF/ jsp/mywizardcancel.jsp" />
</action>
<!-- the second screen of the wizard (back, next and finish) -->
<!-- since finish action is available, bean should validated, note
validation should not necessarily validate if back action requested, you
might delay validation or do conditional validation -->
<action path="/mywizard2" type="actions.MyWizard" name="MyWizard"
validate="true" input="/WEB-INF/ jsp/mywizard2.jsp">
<forward name="back" path="/WEB-INF/ jsp/mywizard1.jsp" />
<forward name="next" path="/WEB-INF/ jsp/mywizard3.jsp" />

154
<forward name="finish" path="/WEB-INF/ jsp/mywizarddone.jsp" />
<forward name="cancel" path="/WEB-INF/ jsp/mywizardcancel.jsp" />
</action>
<!-- the last screen of the wizard (back, finish and cancel only) -->
<action path="/mywizard3" type="actions.MyWizard"name="MyWizard"
validate="true" input="/WEB-INF/ jsp/mywizard3.jsp">
<forward name="back" path="/WEB-INF/ jsp/mywizard2.jsp" />
<forward name="finish" path="/WEB-INF/ jsp/mywizarddone.jsp" />
<forward name="cancel" path="/WEB-INF/ jsp/mywizardcancel.jsp" />
</action>
The pieces of the wizard are as follows:
forms.MyWizard.java - the form bean holding the information required.
actions.MyWizard.java - the actions of the wizard, note the use of LookupDispatchAction
allows for one action class with several methods. All the real work will be done in the 'finish' method.
mywizard[x] .jsp - the data collection jsp's
mywizarddone.jsp - the 'success' page
mywizardcancel.jsp - the 'cancel' page
How can I 'chain' Actions --> Chaining actions can be done by simply using the proper
mapping in your forward entries in the struts-config.xml file. Assume you had the following
two classes:
/* com/AAction.java * /
...
public class AAction extends Action {
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request,HttpServletResponse response) throws Exception {
// Do something
return mapping.findForward("success");
}
}
/* com/BAction.java * /
...
public class BAction extends Action {
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest req, HttpServletResponse res) throws Exception {
// Do something else
return mapping.findForward("success");
}
}
Then you can chain together these two actions with the Struts configuration as shown in the
following excerpt:
...
<action-mappings type= "org.apache.struts.action.ActionMapping">
<action path="/A" type="com.AAction" validate= "false">
< forward name= "success" path= "/B.do" />
</action>
<action path="/B" type="com.BAction" scope= "session" validate= "false">
< forward name= "success" path= "/result.jsp" />
</action>
</action-mappings>
...
Here we are assuming you are using a suffix-based (.do) servlet mapping, which is
recommended since module support requires it. When you send your browser to the web

155
application and name the action A.do (i.e. http://localhost:8080/app/A.do) it will execute
AAction.execute(), which will then forward to the "success" mapping.
This causes the execution of BAction.execute() since the <forward> entry for "success" in the
configuration file uses the .do suffix.
<html:form action= > Action is Defined to forward to target.
A Typical JSP Page to Forward Data to Controller.
<%@ taglib uri="/WEB-INF/struts-bean.tld" prefix="bean" %>
<html>
<head> <title>Struts Application</title> </head>
<body>
<table width="500" border="0" cellspacing="0">
<tr><td>&nbsp;</td></tr>
<tr><td height="68" width="48%">
<div align="left"><img src="images/logowhitespace.gif">
</div></td></tr>
<tr><td>&nbsp;</td></tr>
<tr><td>&nbsp;</td></tr>
<tr><td>&nbsp;</td></tr>
<tr>td>Current Price: <%=request.getAttribute("PRICE")%></td></tr>
<tr><td>&nbsp;</td></tr>
</table> </body>
</html>
ApplicationResources_en_US.properties
userForm.save=Save
userForm.remove= Remove
This class name parameter should contain the fully qualified class name of your custom mapping
class.
In the absence of this parameter, Struts will use the default ActionMapping class.
Use the set-property element to provide the values for the custom property you have defined in
your custom mapping class implementation.
You could then access this property from your Action instance, using the ActionMapping object
passed as an argument by the controller.
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<%@ taglib uri="http://jakarta.apache.org/struts/tags-bean" prefix="bean" %>
<%@ taglib uri="http://jakarta.apache.org/struts/tags-html" prefix="html" %>
<%@ taglib uri="http://jakarta.apache.org/struts/tags-logic" prefix="logic" %>
<html>
<head> <title>Wrox Struts Application</title> </head>
<body><table width="500" border="0" cellspacing="0" cellpadding="0">
<tr> <td>&nbsp;</td></tr>
<tr> <td height="68" width="48%"> <div align="left">
<img src="images/wxmainlogowhitespace.gif"></div></td></tr>
<tr><td>&nbsp;</td></tr><tr><td>&nbsp;</td></tr>
<tr><td>&nbsp;</td></tr>
<tr><td><bean:message key="app.price"/><%= request.getAttribute("PRICE") %>

156
</td></tr>
<tr><td>&nbsp;</td></tr>
</table>
</body>
</html>
ApplicationResource.properties
errors.header=<UL>
errors.prefix=<LI>
errors.suffix=</LI>
errors.footer=</UL>
errors.invalid={0} is invalid.
errors.maxlength={0} can not be greater than {1} characters.
errors.minlength={0} can not be less than {1} characters.
errors.range={0} is not in the range {1} through {2}.
errors.required={0} is required.
errors.byte={0} must be an byte.
errors.date={0} is not a date.
errors.double={0} must be an double.
errors.float={0} must be an float.
errors.integer={0} must be an integer.
errors.long={0} must be an long.
errors.short={0} must be an short.
errors.creditcard={0} is not a valid credit card number.
errors.email={0} is an invalid e-mail address.
errors.cancel=Operation cancelled.
errors.detail={0}
errors.general=The process did not complete. Details should follow.
errors.token=Request could not be completed. Operation is not in sequence.
welcome.title=Struts Application
welcome.heading=Struts Applications in Netbeans!
welcome.message=It's easy to create Struts applications with NetBeans.
ApplicationResources_en_US.properties
app.symbol=Symbol
app.welcomeWELCOME
app.price=PRICE
ApplicationResources_it_IT.properties
app.symbol=Simbolo
struts-config.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts-config PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 1.2//EN"
"http://jakarta.apache.org/struts/dtds/struts-config_1_2.dtd">
<struts-config>
<form-beans>
<form-bean name="LookupForm" type="i18n.LookupForm"/>
</form-beans>
<action-mappings>

157
<action input="/index.jsp" name="LookupForm" path="/i18lookup" scope="session"
type="i18n.LookupAction">
<forward name="success" path="/quote.jsp"/>
<forward name="failure" path="/index.jsp"/>
</action>
</action-mappings>
<message-resources parameter="com/myapp/struts/ApplicationResources"/>
</struts-config>

Struts provides easy to use error management features.


The simplest way is to provide a validate method in Action Form bean or in Action Class.
This validate method is responsible for validating all the fields in the view. (Later, you will learn how
to provide validation methods for every field individually, by customizing the validation framework.)
As a first requirement, include the resource bundle containing the error messages.

Applicationresources.properties
app.symbol=Symbol
app.submit=OK
app.price=Current Price
errors.lookup.symbol.required=<li>A Symbol is Required</li>
errors.lookup.unknown=<li>Unknown Symbol {0}</li>
errors.footer=</ul><hr>
Then provide a validate() method in your form bean.
public ActionErrors validate(ActionMapping mapping,
HttpServletRequest request) {
ActionErrors errors = new ActionErrors();
if ( (symbol == null ) || (symbol.length() == 0) ) {
errors.add("symbol",
new ActionMessage("errors.lookup.symbol.required"));
}
return errors;
ActionErrors Validate() method on failure will add an ActionMessage object to the ActionErrors
object. The ActionErrors object is returned to the Controller servlet, which ensures that the message is
displayed in the browser.Alternatively, the validation can also be performed in the Action class.
The validation for all the fields will be performed in th execute() method, along with any other
processing logic. Like the earlier case, an ActionMessage object is created for every error encountered
and added to the ActionErrors collection.
But instead of returning th ActionErrors object, it is appended to the request object.
ActionErrors errors = new ActionErrors();
errors.add("symbol", new ActionMessage("errors.lookup.unknown",symbol));
// Report any errors we have discovered
if ( !errors.isEmpty() ) {
saveErrors(request, errors);
}
The messages are appropriately displayed by the Framework in the input page.
Please add a <html:errors /> tag in the jsp page, exactly at which location you want the errors to be
displayed.
Since ActionErrors has been deprecated, it is always advisable to use ActionMessages.
Please also note that the ActionErrors/ ActionMessages object stores the ActionError /ActionMessage
objects in a collection of type HashMap.
In fact this HashMap property is a member of ActionMessages which happened to be a superclasss of
ActionErrors.

158

Define your view jsp files.


Inviewjspsuse<bean:messagekey=/>elementwithvaluesspecifiedintermsofthekeys.
<bean:message key="inputForm.firstName"/
Create a plugin element in struts-config.xml after message-resources element

<plug-in className="org.apache.struts.validator.ValidatorPlugIn">
<set-property property="pathnames" value="/WEB-INF/validator-rules.xml,
/WEB-INF/validation.xml"/>
</plug-in>
Include a < form > element under <formset> in validation.xml, which will map every field to the
validation rule provided by Struts.
Struts frame work provided validator-rules.xml maps the rules to its associated methods.Include other
entries like mapping, message resources etc., entries as usual .
Deploy the application.
Implementing Custom Validation
Define your own class with a static method for the required validation.
public class CustomValidatorRules {
public static boolean validatePhoneExt( Object bean,ValidatorAction va,
Field field, ActionMessages errors,
HttpServletRequestrequest){..}

Your form bean should extend ValidatorForm.


publicclassInputFormAllextendsValidatorForm}{
Include a validator element in validator-rules.xml, associating the validation rule name with your
class.

<form-validation>
<global>
<validator name="phoneext"
classname="customvalidation.CustomValidatorRules"
method="validatePhoneExt"
methodParams="java.lang.Object,
org.apache.commons.validator.ValidatorAction,
org.apache.commons.validator.Field,
org.apache.struts.action.ActionMessages,
javax.servlet.http.HttpServletRequest"
msg="errors.phone">
</validator>
.. .. .. ....
Create a form element under formset in validation.xml, which associates the field with the validation
rule.
<formset> <form name="inputFormAll"> <field property="phone"
depends="required,phoneext">
<arg0 key="inputForm.phone" />
</field>
</form>

159
</formset>
Add a plugin element for the validator plugin in struts-config.xml after the message-resources element
<plug-in className="org.apache.struts.validator.ValidatorPlugIn">
<set-property property="pathnames" value="/WEB-INF/validator-rules.xml
/WEB-INF/validation.xml"/>
</plug-in>
Complete the other standard steps associated with the struts application, like creation of Action Class,
Resource bundles, web.xml etc.,
Build and deploy the application
Of course it is also possible to chain actions programmatically, but the power and ease of being able to
"reroute" your web application's structure using the XML configuration file is much easier to maintain. As
a rule, chaining Actions is not recommended. If your business classes are properly factored, you should
be able to call whatever methods you need from any Action, without splicing them together into a
cybernetic Rube Goldberg device. If you must chain Actions, be aware of the following: calling the second
Action from the first Action has the same effect as calling the second Action from scratch. If both of your
Actions change the properties of a formbean, the changes made by the first Action will be lost because
Struts calls the reset() method on the formbean when the second Action is called.
Request preprocessor will be executed ahead of any action classes.

For RequestProcessor protected void processContent(HttpServletRequest request,


HttpServletResponse response) {
super.processContent(request, response);
} RequestProcessor is a class which takes care of calling the
Actions by getting the information from scope stored by
ActionServlet.
The DynaActionForm is not strongly typed as the ActionForm. This means there is no compile time
checking for the form fields. Detecting them at runtime is painful and makes you go through
redeployment. ActionForm can be cleanly organized in packages as against the flat organization in the
Struts Config file. ActionForm were designed to act as a Firewall between HTTP and the Action classes,
i.e. isolate and encapsulate the HTTP request parameters from direct use in Actions. With
DynaActionForm, the property access is no different than using request.getParameter(..).
DynaActionForm construction at runtime requires a lot of Java Reflection (Introspection) machinery that
can be avoided. Time savings from DynaActionForm is insignificant. It doesnt take long for todays IDEs to
generate getters and setters for the ActionForm attributes. (Let us say that you made a silly typo in
accessing the DynaActionForm properties in the Action instance. It takes less time to generate the getters
and setters in the IDE than fixing your Action code and redeploying your web application)
Advantage of Struts 1.2 over struts 1.0
one of them is execute()
1. RequestProcessor class
2. Method perform() replaced by execute() in Struts base Action Class
3. Changes to web.xml and struts-config.xml
4.Declarative exception handling
5.Dynamic ActionForms
6.Plug-ins
7.Multiple Application Modules
8.Nested Tags
9.The Struts Validator
10.Change to the ORO package

160
11.Change to Commons logging
12.Removal of Admin actions
13. Deprecation of the GenericDataSource

whats is RequestProcessor ?
Request processor is a class which is under the controller layer.this class is uesd to acces the client
request from the actionServlet process the req and then dispatches to the next layer i.e Model(Action
class).Finally Action class calls the execute() and and it return the ActionForward to client.
i want to perform certain actionbefore executing my action each time how to do it?
Request Processor class processPreprocess()
Request Processor
RequestDispatcher
Request processor is a class which is
Request Dispatcher is an interface which
responsible for handling request and response
supports for dispatching request from one page
it is provided by struts framework if we want to to another page in a application(page may be a
customize our controller we can make in this
servlet file,JSP etc)
class
Struts 1.0
Struts 1.2
Perform() is used in action class
execute() is used in Action class
Action class Actionform is used
DynaActionform / dispatchAction Class is also
available
nested bean is not available
nested bean tld is available
Action Class
DispatchAction Class
execute() is used.
create own method.
Action Form
Dyna Action Form
contain Action class
no need for Action Form
Identify the error in compile time
Identify the error @ run time since its XML
Time becomes clamble
execution is faster than actionForm
Handle Runtime Exception <global-forwards>
If different Error Page use Action Forward.
Can you replace jdbc with datasource, so how you set parameters to ds like that what you
do with JDBC
Ans : ds is a part of jdbc u cant replace in JDBC u have two types of connections
one of them is JNDI lookup and other is using datasource both are JDBC only
JDBC-Java Database connectivity
if ure using DS u need to pass the DB url,uid,pwd
String url = "jdbcerby:Fred"; Connection con = DriverManager.getConnection(url, "Fernanda", "J8");

u have to harcode uid/pwd

InitialContext ic = new InitialContext() ;


DataSource ds = ic.lookup("java:comp/env/jdbc/myDB");
Connection con = ds.getConnection(); DataSource ds = (DataSource)
org.apache.derby.jdbc.ClientDataSource() ds.setPort(1527);
ds.setHost("localhost"); ds.setUser("APP");
ds.setPassword("APP");
JNDI-Java Naming and Directory Interface its powerful;

i have a struts application ,how many times will the ActionServlet be loaded and invoked?
it will be loaded only once on start of servlet(if u give load on startup as 1) or it will be
loaded on receiving the first request it will be iovoked for every request

161

I have 10 action classes in my application. i need to perform a particular action(say for example
user authentication) before calling any of my action class .how to do it? i want to perform some action
before every action how to do it ?

RequestProcessor contains the processing logic that the ActionServlet performs as it


receives each servlet request from the container. You can customize the request processing behavior
by subclassing this class and overriding the method whose behavior you are interested in changing.
do it in process() method ?
processPreprocess()
STRUTS 2
Struts 2 FrameWork

tries to automate the common tasks

provides a platform for the users to build applications quickly.

based on the OpenSymphony Web Works Framework.

implements the Model-View-Controller (MVC) design pattern.


Model implemented by Action, contain Data and Business Logic.
View implemented by result
Controller implemented by FilterDispatcher, the controller is out front and is the first component to act in
the processing ,map the user request to appropriate action.
General Flow of Struts 2

Data Flow of Struts 2


1.
controller receives the user request and determine which Struts 2 action to invoke.
2.
The framework creates an instance of this action and associate it with the newly created instance
of the ActionInvocation.
3.
the invocation of action should pass through a series of interceptors as defined in the
application's XML file.
4.
The framework calls the ActionInvocations invoke() method to start the execution of the action.

162
5.
Each time the invoke() method is called, ActionInvocation consults its state and executes
whichever interceptor comes next.
6.
ActionInvocation hands control over to the interceptor in the stack by calling the interceptors
intercept() method.
7.
The intercept() method of the interceptor inturn calls the invoke() method of the
ActionInvocation till all the interceptors are invoked, in the end the action itself will be called and the
corresponding result will be returned back to the user.
8.
Some interceptor do work before the action is executed and some do work after the action is
executed. It's not necessary that it should do something each time it is invoked. These interceptors are
invoke both before and after the action.
9.
First all the interceptors are executed in the order they are defined in the stack.
10.
Then the action is invoked and the result is generated.
11.
Again all the interceptors present in the stack are invoked in the reverse order.
ActionContext a global storage area that holds all the data associated with the processing of a request.
When a request comes the params interceptor helps in moving the request data to the ValueStack.
OGNL is an expression language that allows you to reference and manipulate the data on the ValueStack.
OGNL converts the string based form data to their corresponding java types using built-in type
converters.
Again when the results are generated the OGNL converts the java types of the property on the
ValueStack to the string-based HTML output.
ActionContext is thread local which means that the values stored in the ActionContext are unique per
thread, this makes the Struts 2 actions thread safe.
Interceptors are Struts 2 components that execute both before and after the rest of the request
processing. They provide an architectural component in which to define various workflow and
crosscutting tasks so that they can be easily reused as well as separated from other architectural
concerns.
Declarative architecture is a specialized type of configuration that allows a developer to create an
applicationsarchitecturethroughdescriptionratherthanprogrammaticintervention
1.
XML BASED struts.xml
<action name="Login" class="manning.Login">
<result>/AccountPage.jsp</result>
<result name="input">/Login.jsp</result>
</action>
<action name="Registration" >
<result>/Registration.jsp</result>
</action>
<action name="Register" class="manning.Register">
<result>/RegistrationSuccess.jsp</result>
<result name="input">/Registration.jsp</result>
</action>
Annotation Based
@Results({
@Result(name="input", value="/RegistrationSuccess.jsp" )
@Result(value="/RegistrationSuccess.jsp" )
})
public class Login {
public string execute() {
//Business logic for login
}}
2.

163
Intelligent defaults provide out of the box components that solve common domain
workflows without requiring further configuration by the developer, allowing the most common
application tasks to be realized with a minimum of development.
JAR FILES REQUIRED
commons-fileupload-1.2.1
commons-io-1.3.2
commons-logging-1.1
freemarker-2.3.13
junit-3.8.1
ognl-2.6.11
spring-test-2.5.6
struts2-convention-plugin-2.1.6
struts2-core-2.1.6
xwork-2.1.2
Annotations
Index.jsp Page
<%@ 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">
<%@taglib uri="/struts-tags" prefix="s" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Hello World</title>
</head>
<body>
<s:form action="welcome-user" >
<s:textfield name="userName" label="User Name" />
<s:submit />
</s:form>
</body>
</html>
JavaBean class
import com.opensymphony.xwork2.ActionSupport;
public class WelcomeUser extends ActionSupport{
private String userName;
private String message;
public String execute() {
message = "Welcome " + userName;
return SUCCESS;
}
public void setUserName(String userName) {
this.userName = userName;
}
public void setMessage(String message) {
this.message = message;
}
public String getUserName() {

164
return userName;
}
public String getMessage() {
return message;
}
}
Welcome-User.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">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Welcome User</title>
</head>
<body>
<h1>${message}</h1>
</body>
</html
Struts.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/webapp_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
<display-name>Struts2</display-name>
<filter>
<filter-name>struts2</filter-name>
<filter-class>
org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter
</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
Now the coding part is complete. You can run the example by using the following URL
"http://localhost:8080/Struts2/"
The Convention plug-in is the one which does everything in the background. The Convention plug-in does
the following things.

the Convention plug-in looks for the action classes inside the following packages strut, struts2,
action or actions.

Any package that matches these names will be considered as the root package for the
convention plug-in.

165

The action class should either implement com.opensymphony.xwork2.Action interface or the


name of the action class should end with Action. Here we extend our WelcomeUser class from
com.opensymphony.xwork2.ActionSupport which inturn implements com.opensymphony.xwork2.Action.

The Convention plug-in uses the action class name to map the action URL. Here our action class
name is WelcomeUser and the URL is welcome-user. The plug-in converts the camel case class name to
dashes to get the request URL.

Now the Convention plug-in knows which Action class to call for a particular request. The next
step is to find which result to forward based on the return value of the execute method. By default the
Convention plug-in will look for result pages in WEB-INF/content directory.

Now the Convention plug-in knows where to look for results, but it doesn't know which file to
display inside the content directory. The Convention plug-in finds this with the help of the result code
returned by the Action class. If "success" is returned then the Convention plug-in will look for a file name

welcome-user-success.jsp or welcome-user.jsp .
To redirect a result page to results folder

Action / InAction Class


import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Result;
.

@Action(value="/welcome",results={ @Result(name="success",location="/results/successPage.jsp")})
public String execute() {
message = "Welcome " + userName + " !";
return "success";
.
.
Action/ Struts.properties
struts.convention.result.path=/results
The Result annotation maps the result code with the result page. Here the result code " success" is
mapped to the result "/results/successPage.jsp".
Struts.xml
<struts>
<constant name="struts.devMode" value="true" /> ANNOTATION #1
<package name="default" namespace="/" extends="strutsdefault"> <action name="Menu">
ANNOTATION#2
<result>/menu/Menu.jsp</result>
</action>
</package>
<include file="manning/chapterTwo/chapterTwo.xml"/> ANNOTATION #3
<include file="manning/chapterThree/chapterThree.xml"/>
...
<include file="manning/chapterEight/chapterEight.xml"/>
</struts>
(annotation)<#1UseConstantsToTweakStruts2Properties>
(annotation)<#2MenuActionBelongstoaDefaultPackage>
(annotation) <#3IncludeModularizedXMLDocs>
constant element can be used to set framework properties

166
struts.xml is a good place to define some global actions in a default package similar to Struts-config.xml
in Struts 1.x

Useemptyactioncomponentstoforwardtoyourresults,eveniftheyaresimpleJSPsrequiringno
dynamicprocessing.Thiskeepstheapplicationsarchitectureconsistent,pre-wires your workflow in
anticipation of increases in complexity, and hides the real structure of your resources behind the logical
namespace of the Struts 2 actions.
The HelloWorld Action Provides an Execute() Method to Conduct its Work and
JavaBean's Properties to Hold its Data
package manning.annotation;
public class HelloWorld {
private static final String GREETING = "Hello ";
public String execute() { ANNOTATION #1
setCustomGreeting( GREETING + getName() );
return "SUCCESS"; ANNOTATION #2
}
private String name; ANNOTATION #3
private String customGreeting;
public String getName() {
return name; }
public void setName(String name) {
this.name = name; }
public String getCustomGreeting() {
return customGreeting; }
public void setCustomGreeting( String customGreeting ){ this.customGreeting = customGreeting;
}
}
(annotation)<#1TheAction'sBusinessLogic>
(annotation)<#2ControlStringwillSelectResult>
(annotation)<#3JavaBean'sPropertiesHoldtheData>

167
Helloworld using annotations
<filter>
<filter-name>struts2</filter-name>
<filterclass> org.apache.struts2.dispatcher.FilterDispatcher
</filter-class>
<init-param>
<param-name>actionPackages</param-name>
<param-value>manning</param-value> ANNOTATION #1
</init-param>
</filter>
make our actions implement the com.opensymphony.xwork2.Action interface, or use a naming
convention where our class names end with the word Action
Struts 2 Annotations Example - use /results directory for storing our result pages instead of WEBINF/content
Action Class
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Result;
public class WelcomeUserAction {
private String userName;
private String message;
@Action(value="/welcome",results={ @Result(name="success",location="/results/successPage.jsp")})

public String execute() {


message = "Welcome " + userName + " !";
return "success";
}
public void setUserName(String userName) {
this.userName = userName;
}
public void setMessage(String message) {
this.message = message;
}
public String getUserName() {
return userName;
}
public String getMessage() {
return message;
}

The value of the Action annotation is "/welcome", this means that the action will be invoked for the
request URL "/welcome".
Struts.Properties file
struts.convention.result.path=/results
Sample Helloworld Application using Struts2

168

Files Used here.


1.
web.xml
2.
struts.xml
3.
HelloWorld.java
4.
index.jsp
5.
success.jsp
Web.xml
<filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
Struts.xml
<struts>
<package name="default" extends="struts-default">
<action name="HelloWorld" class="HelloWorld">
<result name="SUCCESS">/success.jsp</result>
</action>
</package>
</struts>
index.jsp
<%@taglib uri="/struts-tags" prefix="s" %>
<html>
<head>
<title>Hello World</title>
</head>
<body>
<s:form action="HelloWorld" >
<s:textfield name="userName" label="User Name" />
<s:submit />
</s:form>
</body>
</html>

HelloWorld.java

public class HelloWorld {


private String message;
private String userName;
public HelloWorld() { }
public String execute() {

169
setMessage("Hello " + getUserName());
return "SUCCESS";
}public String getMessage() {
return message;
}public void setMessage(String message) {
this.message = message;
} public String getUserName() {
return userName;
} public void setUserName(String userName) {
this.userName = userName;
}
}
In the execute() method of the HelloWorld action we compose the message to be displayed.

success.jsp

<%@taglib uri="/struts-tags" prefix="s" %>


<html>
<head>
<title>Hello World</title>
</head>
<body>
<h1><s:property value="message" /></h1>
</body>
</html>

Struts 2 ValueStack
In Struts 2 ValueStack is the place where the data associated with processing of the request is
stored. So all the form properties will be stored on the ValueStack.
The name attribute of the UI tag is the one which links the property on the ValueStack.
The next important attribute of the UI tag that you need to understand is the value attribute. If you like
to populate some default

The following code is used to create the register.jsp for above form
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"

170
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<%@taglib uri="/struts-tags" prefix="s"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Register Page</title>
</head>
<body>
<s:form action="Register">
<s:textfield name="userName" label="User Name" />
<s:password name="password" label="Password" />
<s:radio name="gender" label="Gender" list="{'Male','Female'}" />
<s:select name="country" list="countryList" listKey="countryId" listValue="countryName"
headerKey="0" headerValue="Country" label="Select a country" />
<s:textarea name="about" label="About You" />
<s:checkboxlist list="communityList" name="community" label="Community" />
<s:checkbox name="mailingList" label="Would you like to join our mailing list?" />
<s:submit />
</s:form>
</body>
</html>
<s:textfield name="userName" label="User Name" value="defaultName"/>
The property defaultName is stored on the ValueStack so its value will be set to the textfield.
The value set in the label attribute of the UI tags will be used to render the label for that particular field
while generating the HTML code.
<META HTTP-EQUIV="Refresh" CONTENT="0;URL=populateRegister.action">
Based on the mapping done in the struts.xml file the populate() method in the RegisterAction class will
be called
Struts.xml mapping
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration
2.0//EN""http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<package name="default" extends="struts-default">
<action name="*Register" method="{1}" class="RegisterAction">
<result name="populate">/register.jsp</result>
<result name="input">/register.jsp</result>

171
<result name="success">/success.jsp</result>
</action>
</package>
</struts
The register action class contains the form properties and the corresponding getter and setter methods.
It also contains the execute() and populate() methods. In the populate method we first populate the
values and then set the default values for the form fields. The RegisterAction class contains the following
code.
import java.util.ArrayList;
import com.opensymphony.xwork2.ActionSupport;
public class RegisterAction extends ActionSupport {
private String userName;
private String password;
private String gender;
private String about;
private String country;
private ArrayList<Country> countryList;
private String[] community;
private ArrayList<String> communityList;
private Boolean mailingList;
public String populate() {
countryList = new ArrayList<Country>();
countryList.add(new Country(1, "India"));
countryList.add(new Country(2, "USA"));
countryList.add(new Country(3, "France"));
communityList = new ArrayList<String>();
communityList.add("Java");
communityList.add(".Net");
communityList.add("SOA");

community = new String[]{"Java",".Net"};


mailingList = true;
return "populate";

public String execute() { return SUCCESS;}


public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {

172
this.password = password;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getAbout() {
return about;
}
public void setAbout(String about) {
this.about = about;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public ArrayList<Country> getCountryList() {
return countryList;
}
public void setCountryList(ArrayList<Country> countryList) {
this.countryList = countryList;
}
public String[] getCommunity() {
return community;
}
public void setCommunity(String[] community) {
this.community = community;
}
public ArrayList<String> getCommunityList() {
return communityList;
}
public void setCommunityList(ArrayList<String> communityList) {
this.communityList = communityList;
}
public Boolean getMailingList() {
return mailingList;
}
public void setMailingList(Boolean mailingList) {
this.mailingList = mailingList;
}
}
TAGS WITH UI
<s:textfield name="userName" label="User Name" />
<s:password name="password" label="Password" />
<s:radio name="gender" label="Gender" list="{'Male','Female'}" />

173

<s:textarea name="about" label="About You" />


Display the country dropdown using the select tag. specify the option values using the
countryList property of the RegisterAction class. The countryList is of type ArrayList and contain values of
type Country. The Country class has countryId and countryName attribute. The countryName holds the
country value to be display in the frontend and the countryId holds the id value to store it in the
backend. Here countryId is the key and the countryName is the value. We specify this in the select tag
using the listKey and listValue attribute. The first value can be specified using the headerValue attribute
and the corresponding key value is specified using the headerKey attribute.
<s:select name="country" list="countryList" listKey="countryId" listValue="countryName"
headerKey="0" headerValue="Country" label="Select a country" />
<s:checkboxlist list="communityList" name="community" label="Community" /> Similar to Select Tag.
<s:checkbox name="mailingList" label="Would you like to join our mailing list?" /> - return Boolean
value
<s:submit />
Success.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">
<%@taglib uri="/struts-tags" prefix="s"%>
<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Details Page</title>
</head>
<body>
User Name: <s:property value="userName" /><br>
Gender: <s:property value="gender" /><br>
Country: <s:property value="country" /><br>
About You: <s:property value="about" /><br>
Community: <s:property value="community" /><br>
Mailing List: <s:property value="mailingList" />
</body> </html>
DATA TAGS
1.
the property tag, - used to retrive the data from the ValueStack or some other object in the
ActionContext like application or session
Sample Action Class
public class AlbumInfoAction{
private String title;
private Artist artist;
public String populate()
{
.
title = "Thriller";
artist = new Artist("Michael Jackson","King of pop");
return "populate";
}
public String execute() {

174

return "success";
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public Artist getArtist() {
return artist;
}
public void setArtist(Artist artist) {
this.artist = artist;
}

Artist class [bean with setters and getters]


public class Artist {
private String name;
private String bio;
Artist(String name, String bio)
{
this.name = name;
this.bio = bio;
}
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public String getBio() { return bio; }
public void setBio(String bio) { this.bio = bio; }
}
AlbumDetails.jsp
<%@taglib uri="/struts-tags" prefix="s"%>
<html>
<head>
<s:head />
<style type="text/css">
@import url(style.css);
</style>
<title>Album Details</title>
</head>
<body>
<div class="content">
<b>Album Title :</b>
<s:property value="title" /> <br>
<b>Artist Name :</b>
<s:property value="artist.name" />
<br>
<b>Artist Bio :</b>
<s:property value="artist.bio" />
<br>
</div>

175
</body>
</html

Title is the property of the AlbumInfoAction so we can access it directly. But name and bio are
properties of the Artist class so to access them we need to go one step deeper. We need to use a
second-level OGNL expression to access them.
2.

the set tag

The set tag is used to assign a property value to another name. This helps in
accessing the property in a faster and easier way. To access the artist name we need to go one level
deeper and fetch it when we used the property tag, instead you can assign the value to another property
in the ActionContext and access it directly. The following code shows how to do this.
<s:set name="artistName" value="artist.name" />
<s:set name="artistBio" value="artist.bio" />
<b>Album Title :</b> <s:property value="title" /> <br>
<b>Artist Name :</b> <s:property value="#artistName" /> <br>
<b>Artist Bio :</b> <s:property value="#artistBio" /> <br>
The property artistName and artistBio will now be stored in the ActionContext. To
refer then you need to use the following syntax #objectName.
Also place the property value in the session map in the following way. Now the value
artistName and artistBio will persist throughout the session.
<s:set name="artistName" value="artist.name" scope="session" />
<s:set name="artistBio" value="artist.bio" scope="session" />
<b>Album Title :</b> <s:property value="title" /> <br>
<b>Artist Name :</b> <s:property value="#session['artistName']" /> <br>
<b>Artist Bio :</b> <s:property value="#session['artistBio']" /> <br>
In the same way you can also store the values in other maps avaliable in the ActionContext.
the push tag
You can push a value into the ValueStack using the push tag. The value we pushed using push
tag will be on top of the ValueStack, so it can be easily referenced using the first-level OGNL expression
instead of a deeper reference. The following code show how to do this.
3.

<b>Album Title :</b> <s:property value="title" /> <br>


<s:push value="artist">
<b>Artist Name :</b> <s:property value="name" /> <br>
<b>Artist Bio :</b> <s:property value="bio" /> <br>
</s:push>
Bean Tag
1.

use the bean tag to push the value onto the ValueStack

<s:bean name="pkg.CurrencyConverter"> // currencyConverter a java bean class


<s:param name="dollars" value="100" />
100 Dollars = <s:property value="rupees" /> Rupees
</s:bean>
2.

set a top-level reference to it in the ActionContext.

176
<s:bean name="CurrencyConverter" var="converter">
<s:param name="dollars" value="100"></s:param>
</s:bean>
100 Dollars = <s:property value="#converter.rupees" /> Rupees
To create an instance of the bean in the ActionContext we need to specify the instance
name using the var attribute of the bean tag. Here our instance name is converter. Once we do this we
can access the bean values outside the bean tag. Since the value is in the ActionContext we use the #
operator to refer it.
Control Tag
The iterator tag is used to loop over a collection of objects. The iterator tag
can iterate over any Collection, Map, Enumeration, Iterator, or array.
<table class="songTable">
<tr class="even">
<td><b>Title</b></td>
<td><b>Genre</b></td>
</tr>
<s:iterator value="songs" status="songStatus">
<tr class="<s:if test="#songStatus.odd == true"> odd</s:if><s:else>even</s:else>">
<td><s:property value="title" /></td>
<td><s:property value="genre" /></td>
</tr>
</s:iterator>
</table>
We use the iterator tag to iterator over the collection of songs. Here the Song property is of type
ArrayList. To know more about the iterator status we can create an instance of the IteratorStatus object
by specifying a value to the status attribute of the iterator tag. The newly created instance will be placed
in the ActionContext which can be refered using the the following OGNL expression #statusName.
The table show the different properties of the IteratorStatus object.

Name

Return Type Description

index

int

zero-based index value.

count

int

index + 1

first

boolean

returns true if it is the first element

last

boolean

returns true if it is the last element

even

boolean

returns true if the count is an even number.

odd

boolean

returns true if the count is an odd number.

modulus int

takes an int value and returns the modulus of count.

Struts 2 If and Else Tags Example


the if and else tags to highlight the even and odd rows in different colors. We use the
IteratorStatus class methods to find whether the row is even or odd.

177
<s:iterator value="songs" status="songStatus">
<tr class="<s:if test="#songStatus.odd == true"> odd</s:if> <s:else>even</s:else>">
<td><s:property value="title"/></td>
<td><s:property value="genre"/></td>
</tr>
</s:iterator>
The elseif tag is also available. You can use it if there are multiple conditions to check.
OGNL Expression Language
Access the array values in the jsp page
<b>Array Usage Examples</b>
<br><hr>
<b>sampleArray :</b> <s:property value="sampleArray"/> <br>
<b>sampleArray.length :</b> <s:property value="sampleArray.length"/> <br>
<b>sampleArray[0] :</b> <s:property value="sampleArray[0]"/> <br>
<b>[0].sampleArray :</b> <s:property value="[0].sampleArray"/> <br>
<b>top.sampleArray :</b> <s:property value="top.sampleArray"/> <br>
In Action Class
private List<String> sampleList = new ArrayList<String>();
sampleList.add("listItem1");
sampleList.add("listItem2");
sampleList.add("listItem3");
}
public String execute()
{
return "success";
}
public List<String> getSampleList() {
return sampleList; }
public void setSampleList(List<String> sampleList) {
this.sampleList = sampleList;
}

object is on top of the ValueStack we can access it using [0] notation. If our object was in the second
position from the top, we will access it using the [1] notation.
Also do this using the top keyword. top returns the value on top of the ValueStack
access the ArrayList values in the jsp page
<b>List Usage Examples</b>
<br><hr>
<b>sampleList :</b> <s:property value="sampleList"/> <br>
<b>sampleList.size :</b> <s:property value="sampleList.size"/> <br>
<b>sampleList[0] :</b> <s:property value="sampleList[0]"/> <br>
In action class
private Map<Integer,String> sampleMap = new HashMap<Integer,String>();
private String carMake;
{
sampleMap.put(new Integer(1), "one");
sampleMap.put(new Integer(2), "two");

178
sampleMap.put(new Integer(3), "three");
}
public String execute()
{
return "success";
}
public Map<Integer, String> getSampleMap() {
return sampleMap;
}
public void setSampleMap(Map<Integer, String> sampleMap) {
this.sampleMap = sampleMap;
}
public String getCarMake() {
return carMake;
}
public void setCarMake(String carMake) {
this.carMake = carMake;
}
Map values in the jsp page
<b>Map Usage Examples</b>
<br><hr>
<b>sampleMap[1] :</b> <s:property value="sampleMap[1]"/> <br>
<b>sampleMap.size :</b> <s:property value="sampleMap.size"/> <br>
Or. In JSP Page to display a MAP
<s:select list="#{'make1':'Ford', 'make2':'Honda', 'make3':'Toyota'}" name="carMake" label="Select ">
</s:select>
In Action Class
private Map<Integer,String> sampleMap = new HashMap<Integer,String>();
sampleMap.put(new Integer(1), "one");
sampleMap.put(new Integer(2), "two"); sampleMap.put(new Integer(3), "three");
to access user.name 2nd level use the foll
<b>user.name :</b> <s:property value="user.name"/> <br>
To call an action class method
<b>quote() :</b> <s:property value="quote()"/> <br>
Interceptors Execution before and After Action class Execution
In this example you will see how the interceptors are invoked both before and after the execution of the
action and how the results are rendered back to the user. Let's understand this with the help of the
following diagram.

179

The following actions happen in a sequence when a request comes to the Struts 2 framework.
EXECUTION FLOW OF INTERCEPTORS
1. Framework first finds which Action class to invoke for this request and discovers the interceptors
associated with the action mapping.
2. the Framework creates an instance of ActionInvocation and calls its invoke() method. At this point the
Frameworks hands the control over to the ActionInvocation for further processing of the request.
3. ActionInvocation is the one which encapsulates the action and the associated intercteptors.
4. ActionInvocation knows in which sequence the interceptors should be invoked.
5. ActionInvocation now invokes the intercept() method of the first interceptor in the stack.
The LoggingInterceptor's intercept() method contains the following code.
public String intercept(ActionInvocation invocation) throws Exception {
//Pre processing
logMessage(invocation, START_MESSAGE);
String result = invocation.invoke();
//Post processing
logMessage(invocation, FINISH_MESSAGE);
return result; }
6. First the logMessage() method is called and the message is logged, this is the pre processing done by
the logger interceptor, then the invoke() method of the ActionInvocation is again called, this time the
ActionInvocation will call the next intercetor in the stack and this cycle will continue till the last
interceptor in the stack.
7. After the execution of all the interceptors the action class will be invoked. Finally a result string will be
returned and the corresponding view will be rendered. This is the normal flow of events.
8. But what if an validation error occurs, in this case the request processing will be stopped. No further
interceptors will be invoked. Action will not be executed. The control flow changes, now the interceptors
executed so far will be invoked in the reverse order to do the post processing if any and finally the result

180
will be rendered to the user.
9. Come back to the normal flow. In our case the logger interceptor is the only interceptor in the stack,
so after logging the "START_MESSAGE", the ActionInvocation's invoke() method will invoke the action.
Our action simply returns "success", then again the logger interceptor will be invoked to do the post
processing, this time the "FINISH_MESSAGE" is logged and the result is returned. Based on the result
the corresponding view will be rendered to the user.

benefits by using the interceptors.


1. Extremely flexiable.
2. Cleaner and focused Action classes.
3. Provides code readability and code reuse.
4. Testing process becomes easier.
We can add only the interceptors we need to the stack and customising the action processing for each
request.
In the index.jsp page we forward the request to the "TestLogger" URL.
<META HTTP-EQUIV="Refresh" CONTENT="0;URL=TestLogger.action">
The TestLogger URL is mapped to the TestLoggerAction class in the struts.xml file.
.<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<package name="test" extends="struts-default">
<action name="TestLogger" class="TestLoggerAction">
<interceptor-ref name="logger" />
<result name="success">/success.jsp</result>
</action>
</package>
</struts>
The interceptor-ref element is used to add a interceptor reference to the action. All the interceptors are
defined in the struts-default package of the struts-default.xml file.
Now the execute() method of the TestLoggerAction class will be invoked. The execute() method just
prints a statement and returns success.
public class TestLoggerAction {
public String execute()
{
System.out.println("Inside Action");
return "success";
}
}
Based on the mapping in the XML configuration file the user will be forwarded to the success page.
1. INFO: Starting execution stack for action //TestLogger
2. Inside Action
3. INFO: Finishing execution stack for action //TestLogger
CREATE OUR OWN Interceptors
Struts 2 comes with a set of pre defined interceptors and interceptor stacks which you can use out of the
box. The struts-default.xml file contains the struts-default package which defines all the interceptors and

181
the interceptor stacks.
When you extend your package from the struts-default package by default the defaultStack will be used
for all the actions in your package configured in struts-default.xml.
<default-interceptor-ref name="defaultStack"/>
The interceptor-stack element is used to create an interceptor stack. A stack contains a group of
interceptors. Each interceptor in the stack is defined using the interceptor-ref element.
Three methods in our SampleAction class, populate() ,execute() and validate(). Since we extend our
class from ActionSupport which in turn implements the Validateable interface, the validate() method of
the action class will be called by the workflow interceptor. By default the validate() method will be called
during the execution of both populate() and execute() methods but we need to validate only when the
execute() method is invoked.
We do this by specifying the populate method in the excludeMethods parameter of the validation
interceptor.
The struts.xml file contains the following code.
.<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<package name="default" extends="struts-default">
<interceptors>
<interceptor-stack name="exampleStack">
<interceptor-ref name="exception" />
<interceptor-ref name="alias" />
<interceptor-ref name="servletConfig" />
<interceptor-ref name="prepare" />
<interceptor-ref name="i18n" />
<interceptor-ref name="chain" />
<interceptor-ref name="debugging" />
<interceptor-ref name="profiling" />
<interceptor-ref name="scopedModelDriven" />
<interceptor-ref name="modelDriven" />
<interceptor-ref name="fileUpload" />
<interceptor-ref name="checkbox" />
<interceptor-ref name="staticParams" />
<interceptor-ref name="actionMappingParams" />
<interceptor-ref name="params">
<param name="excludeParams"> dojo\..*,^struts\..*</param>
</interceptor-ref>
<interceptor-ref name="conversionError" />
<interceptor-ref name="validation">
<param name="excludeMethods">populate</param>
</interceptor-ref>
<interceptor-ref name="workflow">
<param name="excludeMethods"> input,back,cancel,browse</param>
</interceptor-ref>
</interceptor-stack>
</interceptors>
<action name="*Sample" method="{1}" class="SampleAction">
<interceptor-ref name="exampleStack" />

182
<result name="populate">/first.jsp</result>
<result name="success">/success.jsp</result>
</action>
</package>
</struts>
changed the excludeMethods of the validation interceptor, rest all is similar to the defaultStack. This is
just to show you how to create your own interceptor stack, you can also achieve the same in a much
simpler way.
You can extend your stack from the defaultStack and override the excludeMethods parameter of the
validation interceptor in the following way to achieve the same result.
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<package name="default" extends="struts-default">
<action name="*Sample" method="{1}" class="SampleAction">
<interceptor-ref name="defaultStack" >
<param name="validation.excludeMethods"> populate</param>
</interceptor-ref>
<result name="populate">/first.jsp</result>
<result name="success">/success.jsp</result>
</action>
</package>
</struts>
Our SampleAction class contains the following code.
import com.opensymphony.xwork2.ActionSupport;
public class SampleAction extends ActionSupport{
private static final long serialVersionUID = 1L;
public void validate()
{
System.out.println("validate() method called");
}
public String populate()
{
System.out.println("populate() method called");
return "populate";
}
public String execute()
{
System.out.println("execute() method called");
return SUCCESS;
}
}
When you run the code using the defaultStack without any changes. The following messages gets
printed in the console.
1.validate() method called
2.populate() method called
3.validate() method called
4.execute() method called
When you run the code the using the exampleStack we just created. The follwing messages gets printed
in the console.

183
1.populate() method called
2.validate() method called
3.execute() method called
As you can see the validate() method is not invoked during populate. In this way you can customise the
stack base on your requirement.
Dispatch Action
Struts 1 DispatchAction helps in grouping a set of related functions into a single action. In Struts
2 all the Actions by default provide this functionality. To use this functionality need to create different
methods with the similar signature of the execute() method, only the name of the method changes.
import com.opensymphony.xwork2.ActionSupport;
public class UserAction extends ActionSupport{
public String execute() {
message = "Inside execute method";
return SUCCESS;
}
public String add() {.}
publicStringupdate{..}
bean[setter and getter] methods
Can have execute() method along with other methods and need to specify which method in the action
class will be called while configuring the action mapping. A separate action mapping needs to be created
for each method in the action class.
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<package name="default" extends="struts-default">
<action name="User" class="UserAction">
<result name="success">/success.jsp</result>
</action>
<action name="addUser" method="add" class="UserAction">
<result name="success">/success.jsp</result>
</action>
<action name="updateUser" method="update" class="UserAction">
<result name="success">/success.jsp</result>
</action>
<action name="deleteUser" method="delete" class="UserAction">
<result name="success">/success.jsp</result>
</action>
</package>
</struts>
Note that we use the same action class in all the action mappings. When the request URL is " User" the
execute() method in the UserAction class will be invoked. When the request URL is "addUser" the add()
method in the UserAction class will be invoked, this is specified using the method attribute of the action
tag. Similarly for update and delete request the updateUser() and deleteUser() methods will be invoked
respectively.

184
Configuring a seperate action mapping for each method in the action class can be avoided by using an
another feature of Struts 2 called Dynamic Method Invocation.
In the index.jsp page we create four different buttons to invoke the different methods in the UserAction
class. The submit tag is used to create the buttons in the jsp page.
<%@ 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">
<%@taglib uri="/struts-tags" prefix="s" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<s:form action="User" >
<s:submit />
<s:submit action="addUser" value="Add" />
<s:submit action="updateUser" value="Update" />
<s:submit action="deleteUser" value="Delete" />
</s:form>
</body>
</html>
Now lets execute the example. On running the example the following page will be displayed to the user.
When the user click a button the appropriate method in the UserAction class gets invoked.
Dynamic Method Innovation
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<package name="default" extends="struts-default">
<action name="*User" method="{1}" class=" UserAction">
<result name="success">/success.jsp</result>
</action>
</package>
</struts>
<%@ 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">
<%@taglib uri="/struts-tags" prefix="s" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>

185
<body>
<s:form action="User" >
<s:submit />
<s:submit action="addUser" value="Add" />
<s:submit action="updateUser" value="Update" />
<s:submit action="deleteUser" value="Delete" />
</s:form>
</body>
</html>
Replaced all the method names with an asterisk symbol. The word that matches for the first asterisk will
be substituted for the method attribute. So when the request URL is "addUser" the add() method in the
UserAction class will be invoked.
Struts 2 Validation
Struts 2 Validation Example
Validate a login page using Struts 2. Let's first create the login page. use Struts UI tags to create the
login page. The <s:head /> tag should be placed in the head section of the HTML page. The s:head tag
automatically generates links to the css and javascript libraries that are necessary to render the form
elements.
The s:form tag contains all the form elements. The action attribute contains the action name to wich the
form should be submitted. This action name should be same as the one specified in the XML declarative
architecture. In this example we use struts.xml file to do the configuration.
The textfield tag is used create a text box. The label attribute of the textfield tag contains the name to
be displayed on the page and the name attribute contains the name of the property in the action class to
be mapped. The password tag is same as the textfield tag except that the input value is masked. The
submit tag is used to create a submit button, the value "Login" represents the label of the button.
<%@taglib uri="/struts-tags" prefix="s" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Login Page</title>
<s:head />
</head>
<body>
<s:form action="Login">
<s:textfield name="userName" label="User Name" />
<s:password name="password" label="Password" />
<s:submit value="Login" />
</s:form>
</body>
</html>
When the user clicks the Login button the request will be forwarded to the Login action.
We do the action mapping using the struts.xml file. First we need to create a package for our action.
<struts>
<package name="default" extends="struts-default">
<action name="Login" class="Login">
<result name="input">/login.jsp</result>
<result name="success">/success.jsp</result>
</action>
</package>

186
</struts>
Here our "default" package extends "struts-default" package. By extending the "struts-default" package
the action will by default inherit the set of interceptors defined in the defaultstack. The "struts-default"
package is defined in the struts-default.xml file.
All the common tasks done by the Actions are seperated and placed in different interceptors. You can
define an interceptor stack for each action. Most commonly used interceptors are grouped in
defaultstack of the struts-default package. The defaultstack will be sufficient in most cases. The
inteceptors will be fired in the order in which they are declared in the stack both before and after the
action is executed.
Here the "Login" action is mapped to the "Login" class in the "vaannila" package. The results are defined
using the "<result>" element. If any validation errors occur the user will be forwarded to the login.jsp
page. If the login is successfull then the user will be forwarded to the success.jsp page.
public class Login extends ActionSupport {
private String userName;
private String password;
public Login() {
}
public String execute() {
return SUCCESS;
}
public void validate() {
if (getUserName().length() == 0) {
addFieldError("userName", "User Name is required");
} else if (!getUserName().equals("Eswar")) {
addFieldError("userName", "Invalid User");
}
if (getPassword().length() == 0) {
addFieldError("password", getText("password.required"));
}
}
//.Settersandgettersforusernameandpassword
}
The ActionSupport class implements Action interface which exposes the execute() method.
The following constants are declared in the Action interface which can be used as return values in the
execute() method.
public static final String ERROR = "error"
public static final String INPUT = "input"
public static final String LOGIN = "login"
public static final String NONE = "none"
public static final String SUCCESS = "success"
ERROR is returned when the action execution fails.
INPUT is returned when the action requires more input from the user.
LOGIN is returned when the user is not logged into the system.
NONE is returned when the action execution is successfull and there are no views to display.
SUCCESS is returned when the action executed successfully and the corresponding result is displayed to
the user.
Now lets see the roles played by the different interceptors.
The params interceptor helps in transfering the request data onto the action object.
The workflow interceptor controls the flow of cotrol.
The workflow interceptor checks whether the action implements the Validateable interface , if it does,
the workflow interceptor will invoke the validate() method of the Action class.

187
In the validate() method we validate the user name and the password. If the validation fails an error is
added using the addFiledError() method.
The validate() method doesn't return any errors, instead it stores all the errors with the help of the
ValidationAware interface.
Now the workflow interceptor will check any validation errors has occured. If any error has occured the
workflow interceptor will stop the request processing and transfer the control to the input page with the
appropriate error messages.
Login.proerties
password.required = Password is required.
Validation using XML
The naming convention of the XML validation file should be ActionClass-Validation.xml. Here our Action
Class name is "Login.java" and the XML validation file name is "Login-Validation.xml".
The Login-Validation.xml file contains the following code.
<!DOCTYPE validators PUBLIC "-//OpenSymphony Group//XWork Validator 1.0.2//EN"
"http://www.opensymphony.com/xwork/xwork-validator-1.0.2.dtd">
<validators>
<field name="userName">
<field-validator type="requiredstring">
<message>User Name is required.</message>
</field-validator>
</field>
<field name="password">
<field-validator type="requiredstring">
<message key="password.required" />
</field-validator>
</field> </validators>
The field element contains the name of the form property that needs to be validated. The
filed-validator element inside the field element contains the type of validation that needs to be
performed.
specify the error message directly using the message element or you can use the properties file to define
all the errror messages and use the key attribute to specify the error key.
Note the properties file should also have the same name as the Action class.
The Login Action class contains the following code.
public class Login extends ActionSupport {
private String userName;
private String password;
public Login() {
}
public String execute() {
return SUCCESS;
}
.//setterandgetter
Login.jsp
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@taglib uri="/struts-tags" prefix="s" %>
<html>
<head>

188
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Login Page</title>
<s:head />
</head>
<body>
<s:form action="LoginAction">
<s:textfield name="userName" label="User Name" />
<s:password name="password" label="Password" />
<s:submit value="Login" />
</s:form>
</body>
</html>
The <s:head /> tag is used to include the required css and js file for the selected theme. By default the
xhtml theme is used.
Domain Object as Java Bean property
Transferring the data to the domain object is automatically done by the params interceptor.
getUser().getAge();
InJSPitsreferredas
<body>
<s:form action="UserAction" >
<s:textfield name="user.name" label="User Name" />
<s:textfield name="user.age" label="Age" />
<s:radio name="user.sex" label="Sex" list="{'M','F'}" />
.
In Result.jsp page
User Name :<s:property value="user.name" /><br>
Age :<s:property value="user.age" /><br>
Hobbies :<s:property value="user.hobby" /><br>
Country :<s:property value="user.country" /><br>
Model Driven Inferface.
To create a ModelDriven Action our Action class should implement the ModelDriven interface and should
include the modelDriven interceptor. The modelDriven interceptor is already included in the default stack.
The next step is to implement the getModel() method in such a way that it returns the application domain
object, in our example we return the User object.
When using the ModelDriven method,need to initialize the User object ourselves. The framework will
automatically transfers the form data into the User object.
public class UserAction extends ActionSupport implements ModelDriven {
private User user = new User();
public UserAction() {
}
public Object getModel() {
return user;
}
public String execute() {
return SUCCESS;
}
public User getUser() {
return user;
}
public void setUser(User user) { this.user = user; }
}
You can directly access the user attributes like name, age etc in Action use the following syntax.

189
user.getXXX();
The User class contains the following attributes and the corresponding getter and setter methods.
public class User {
private String name;
private int age;
private String sex;
private String[] hobby;
private String country;
public
public
public
public
public
public
public
public
public
public

String getName() {
return name; }
void setName(String name) { this.name = name; }
int getAge() {
return age; }
void setAge(int age) { this.age = age;
}
String getSex() {
return sex; }
void setSex(String sex) {
this.sex = sex;
}
String[] getHobby() { return hobby; }
void setHobby(String[] hobby) { this.hobby = hobby; }
String getCountry() { return country; }
void setCountry(String country) { this.country = country;

}
}
In the jsp page the user attributes can be accessed directly. To refer the user's age, the value of the
name attribute should be
name=age;
name = "age"
index.jsp
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<%@taglib uri="/struts-tags" prefix="s" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>User Details</title>
</head>
<body>
<s:form action="UserAction" >
<s:textfield name="name" label="User Name" />
<s:textfield name="age" label="Age" />
<s:radio name="sex" label="Sex" list="{'M','F'}" />
<s:checkboxlist name="hobby" label="Hobby" list="{'Music','Art','Dance'}"/>
<s:select name="country" label="Country"
list="{'Select','India','USA','France','Spain'}" />
<s:submit />
</s:form>
</body>
</html>
The result.jsp
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<%@taglib uri="/struts-tags" prefix="s" %>
<html>

190
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>User Details</title>
</head>
<body>
<h2>User Details</h2>
<hr>
User Name :<s:property value="name" /><br>
Age :<s:property value="age" /><br>
Hobbies :<s:property value="hobby" /><br>
Country :<s:property value="country" /><br>
</body>
</html>
ModelDriven is like an Action Form in Struts 1.x
FileUploadInterpreter Inbuilt
Input Form.jsp
<s:form action="fileUpload" method="post" enctype="multipart/form-data" >
<s:file name="userImage" label="User Image" />
<s:submit />
</s:form>
PublicClassFileUploadActionextendsActionSupport{.}
<%@ 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">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>File Upload</title>
</head>
<body>
You have uploaded the following file.
<hr>
File Name : ${userImageFileName} <br>
Content Type : ${userImageContentType}
</body>
</html>
Now let's run the example.
validate either programmatically or declaratively. Validate the file in the validate() method of the
FileUploadAction class. You can get the file using the getX() method and the file type type using the
getXContentType() method.
The only change we need to do is to add few parameters to the fileUpload interceptor. So we copy
the defaultStack from the struts-default.xml and paste it in our struts.xml file and rename the stack to
fileUploadStack. Our struts.xml file contains the following code.
We can validate either programmatically or declaratively. Let's see how to do programmatically first.
Validate the file in the validate() method of the FileUploadAction class. You can get the file using the
getX() method and the file type type using the getXContentType() method.

191
In this example we validate declaratively. To do this we need to create our own interceptor stack. The
only change we need to do is to add few parameters to the fileUpload interceptor. So we copy the
defaultStack from the struts-default.xml and paste it in our struts.xml file and rename the stack to
fileUploadStack. Our struts.xml file contains the following code.

<!DOCTYPE struts PUBLIC 02."-//Apache Software Foundation//DTD Struts Configuration


2.0//EN""http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<package name="fileUploadPackage" extends="struts-default">
<interceptors>
<interceptor-stack name="fileUploadStack">
<interceptor-ref name="exception" />
<interceptor-ref name="alias" />
<interceptor-ref name="servletConfig" />
<interceptor-ref name="prepare" />
<interceptor-ref name="i18n" />
<interceptor-ref name="chain" />
<interceptor-ref name="debugging" />
<interceptor-ref name="profiling" />
<interceptor-ref name="scopedModelDriven" />
<interceptor-ref name="modelDriven" />
<interceptor-ref name="fileUpload">
<param name="maximumSize">10240</param>
<param name="allowedTypes"> image/jpeg,image/gif,image/png</param>
</interceptor-ref>
<interceptor-ref name="checkbox" />
<interceptor-ref name="staticParams" />
<interceptor-ref name="actionMappingParams" />
<interceptor-ref name="params">
<param name="excludeParams"> dojo\..*,^struts\..*</param>
</interceptor-ref>
<interceptor-ref name="conversionError" />
<interceptor-ref name="validation">
<param name="excludeMethods"> input,back,cancel,browse</param>
</interceptor-ref>
<interceptor-ref name="workflow">
<param name="excludeMethods"> input,back,cancel,browse</param>
</interceptor-ref>
</interceptor-stack>
</interceptors>
<action name="fileUpload" class="FileUploadAction">
<interceptor-ref name="fileUploadStack" />
<result name="input">/index.jsp</result>
<result name="success">/success.jsp</result>
</action>
</package>
</struts>
The maximumSize value is set in bytes. Here we set the maximumSize to 10kb. The
allowedTypes indicate the file types that can be uploaded. Here we set it to only image files like

192
image/jpeg,image/gif,image/png.
Struts 2 spring Integration .
In Web.xml - Add the ContextLoaderListener
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
1.

Add the Applicationcontext.xml file


<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/applicationContext*.xml</param-value>
</context-param>
you don't specify the contextConfigLocation context parameter, the ContextLoaderListener will look for a
file called /WEB-INF/applicationContext.xml to load. Once the context files are loaded, Spring creates a
WebApplicationContext object based on the bean definitions and stores it in the ServletContext of one's
web application.
All Java web frameworks are built on top of the Servlet API, and so one can use the following code
snippet to get access to this 'business context' ApplicationContext created by the ContextLoaderListener.
WebApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(servletContext);

1. The WebApplicationContextUtils class is for convenience, so you don't have to remember the name of the
ServletContext attribute. Its getWebApplicationContext() method will return null if an object doesn't exist
under the WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE key. Rather than
risk getting NullPointerExceptions in your application, it's better to use the
getRequiredWebApplicationContext() method. This method throws an exception when the
ApplicationContext is missing.
Struts2 with Tiles integration
Web.xml
<context-param>
<param-name> org.apache.tiles.impl.BasicTilesContainer.DEFINITIONS_CONFIG </param-name>
<param-value>/WEB-INF/tiles.xml</param-value>
</context-param>
Listner
<listener>
<listener-class>org.apache.struts2.tiles.StrutsTilesListener</listener-class>
</listener>
Web.xml - filter
<filter>
<filter-name>struts2</filter-name>
<filter-class>
org.apache.struts2.dispatcher.ng.filter. StrutsPrepareAndExecuteFilter
</filter-class>
</filter>

193
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
The tiles.xml file contains the following tile definitions
.<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE tiles-definitions PUBLIC
"-//Apache Software Foundation//DTD Tiles Configuration 2.0//EN"
"http://tiles.apache.org/dtds/tiles-config_2_0.dtd">
<tiles-definitions>
<definition name="baseLayout" template="/baseLayout.jsp">
<put-attribute name="title" value="Template"/>
<put-attribute name="header" value="/header.jsp"/>
<put-attribute name="menu" value="/menu.jsp"/>
<put-attribute name="body" value="/body.jsp"/>
<put-attribute name="footer" value="/footer.jsp"/>
</definition>
<definition name="welcome" extends="baseLayout">
<put-attribute name="title" value="Welcome"/>
<put-attribute name="body" value="/welcome.jsp"/>
</definition>
<definition name="friends" extends="baseLayout">
<put-attribute name="title" value="Friends"/>
<put-attribute name="body" value="/friends.jsp"/>
</definition>
<definition name="office" extends="baseLayout">
<put-attribute name="title" value="Office"/>
<put-attribute name="body" value="/office.jsp"/>
</definition>
</tiles-definitions>
Define a "baseLayout" that contains a title, header, menu, body and footer regions. The header, menu
and footer region remains the same for all the layouts only the title and body content changes.
In the baseLayout.jsp page we create a classic tiles layout as shown below.
<%@ taglib uri="http://tiles.apache.org/tags-tiles" prefix="tiles" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>
<tiles:insertAttribute name="title" ignore="true" />
</title>
</head>
<body>
<table border="1" cellpadding="2" cellspacing="2" align="center">
<tr>
<td height="30" colspan="2">

194
<tiles:insertAttribute name="header" />
</td>
</tr>
<tr>
<td height="250">
<tiles:insertAttribute name="menu" />
</td>
<td width="350">
<tiles:insertAttribute name="body" />
</td>
</tr>
<tr>
<td height="30" colspan="2">
<tiles:insertAttribute name="footer" />
</td>
</tr>
</table>
</body>
</html>
the following tiles lib files required.
truts2-tiles-plugin-2.1.6.jar
tiles-api-2.1.2
tiles-compat-2.1.2
tiles-core-2.1.2
tiles-jsp-2.1.2
tiles-servlet-2.1.2
commons-beanutils-1.8.0
commons-digester-1.8.1
STRUTS 2 with Hibernate Integration
USERDAOIMPL CLASS
import java.util.List;
import org.hibernate.Session;
import org.hibernate.Transaction;
import com.googlecode.s2hibernate.struts2.plugin.annotations.SessionTarget;
import com.googlecode.s2hibernate.struts2.plugin.annotations.TransactionTarget;
import com.domain.User;
public class UserDAOImpl implements UserDAO {
@SessionTarget
Session session;
@TransactionTarget
Transaction transaction;
@SuppressWarnings("unchecked")
@Override
public List<User> listUser() {
List<User> courses = null;

195
try {
courses = session.createQuery("from User").list();
} catch (Exception e) {
e.printStackTrace();
}
return courses;
}

@Override
public void saveUser(User user) {
try {
session.save(user);
} catch (Exception e) {
transaction.rollback();
e.printStackTrace();
}
}

For the session and transaction injection to happen throught the plug-in the org.hibernate. Session and
org.hibernate.Transaction objects should be declared as class variables and not at method level.
Keep these variables in a generic DAO class and extend all the other DAO's from it. When using this plugin there is no need to explicitly commit the transaction and close the session, both will be done
automatically.
The "transaction.rollback()" should be used only in the methods that updates the database.
In the hibernate configuration file, we configure it to work with the hsqldb database.
Hibernate.fg.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class"> org.hsqldb.jdbcDriver </property>
<property name="hibernate.connection.url"> jdbc:hsqldb:hsql://localhost </property>
<property name="hibernate.connection.username">sa</property>
<property name="connection.password"></property>
<property name="connection.pool_size">1</property>
<property name="hibernate.dialect"> org.hibernate.dialect.HSQLDialect </property>
<property name="show_sql">true</property>
<property name="hbm2ddl.auto">create</property>
<mapping class="com.domain.User" />
</session-factory> </hibernate-configuration>
The domain object User class is shown below.
package com.domain;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity

196
@Table(name="USER")
public class User {
private
private
private
private
private
private
private

Long id;
String name;
String password;
String gender;
String country;
String aboutYou;
Boolean mailingList;

@Id
@GeneratedValue
@Column(name="USER_ID")
public Long getId() { return id; }
public void setId(Long id) { this.id = id; }
@Column(name="USER_NAME")
public String getName() { return name; }
public void setName(String name) {
this.name = name;
// setters and getters

In the UserAction class we have two methods add() and list() to add and list all users respectively.
package com.web;
import java.util.ArrayList;
import java.util.List;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import com.dao.UserDAO;
import com.dao.UserDAOImpl;
import com.domain.User;
public class UserAction extends ActionSupport implements ModelDriven<User> {
private static final long serialVersionUID = -6659925652584240539L;
private User user = new User();
private List<User> userList = new ArrayList<User>();
private UserDAO userDAO = new UserDAOImpl();
@Override
public User getModel() {

return user; }

public String add() {


userDAO.saveUser(user); return SUCCESS; }
public String list(){ userList = userDAO.listUser(); return SUCCESS;
}
// setters and getters
}
For the session and transaction injection to happen through the plug-in, the UserDAO should be a class
level declaration and should not be declared at method level.
To use this plug-in you need to extend the package from hibernate-default package. To configure this
you can either use XML or annotations,
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<package name="default" extends="hibernate-default">

197
<action name="addUser" method="add" class="com.web.UserAction">
<result name="success" type="redirect">listUser</result>
</action>
<action name="listUser" method="list" class="com.web.UserAction">
<result name="success">/register.jsp</result>
</action>
</package>
</struts>
The register.jsp page is shown below.
<%@ 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">
<%@taglib uri="/struts-tags" prefix="s"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Registration Page</title>
<s:head />
<style type="text/css">
@import url(style.css);
</style>
</head>
<body>
<s:form action="addUser">
<s:textfield name="name" label="User Name" />
<s:password name="password" label="Password" />
<s:radio name="gender" label="Gender" list="{'Male','Female'}" />
<s:select name="country" list="{'India','USA','UK'}" headerKey=""
headerValue="Country" label="Select a country" />
<s:textarea name="aboutYou" label="About You" />
<s:checkbox name="mailingList"
label="Would you like to join our mailing list?" />
<s:submit />
</s:form>
<s:if test="userList.size() > 0">
<div class="content">
<table class="userTable" cellpadding="5px">
<tr class="even">
<th>Name</th>
<th>Gender</th>
<th>Country</th>
<th>About You</th>
<th>Mailing List</th>
</tr>
<s:iterator value="userList" status="userStatus">
<tr
class="<s:if test="#userStatus.odd == true ">odd</s:if><s:else>even</s:else>">
<td><s:property value="name" /></td>
<td><s:property value="gender" /></td>

198
<td><s:property value="country" /></td>
<td><s:property value="aboutYou" /></td>
<td><s:property value="mailingList" /></td>
</tr>
</s:iterator>
</table>
</div>
</s:if>
</body>
</html>
Create Read Update Delete with DB DAOImpl Class
public void saveOrUpdateUser(User user) {
try {
session.saveOrUpdate(user);
} catch (Exception e) {
transaction.rollback();
e.printStackTrace();
}
}
/**
* Used to delete a user.
*/
@Override
public void deleteUser(Long userId) {
try {
User user = (User) session.get(User.class, userId);
session.delete(user);
} catch (Exception e) {
transaction.rollback();
e.printStackTrace();
}
}
/**
* Used to list all the users.
*/
@SuppressWarnings("unchecked")
@Override
public List<User> listUser() {
List<User> courses = null;
try {
courses = session.createQuery("from User").list();
} catch (Exception e) {
e.printStackTrace();
}
return courses;
}
/**
* Used to list a single user by Id.
*/
@Override
public User listUserById(Long userId) {
User user = null;
try {
user = (User) session.get(User.class, userId);
} catch (Exception e) {

199

e.printStackTrace();
}
return user;

}
// Load Setters and getters as a new File
Our UserAction implements ModelDriven interface, so the domain object User will be exposed as a model
object. Use ActionContext.getContext().get(ServletActionContext. HTTP_REQUEST) method to access the
HttpServeletRequest object in action.
package com.web;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import com.dao.UserDAO;
import com.dao.UserDAOImpl;
import com.domain.User;
public class UserAction extends ActionSupport implements ModelDriven<User> {
private static final long serialVersionUID = -6659925652584240539L;
private User user = new User();
private List<User> userList = new ArrayList<User>();
private UserDAO userDAO = new UserDAOImpl();
@Override
public User getModel() {
return user;
}
/**
* To save or update user. * @return String
public String saveOrUpdate()
{
userDAO.saveOrUpdateUser(user);
return SUCCESS;
}
/** To list all users. * @return String
public String list() {
userList = userDAO.listUser();
return SUCCESS;
}

*/

*/

/** * To delete a user.


* @return String */
public String delete() {
HttpServletRequest request = (HttpServletRequest) ActionContext.getContext().get(
ServletActionContext.HTTP_REQUEST);
userDAO.deleteUser(Long.parseLong( request.getParameter("id")));
return SUCCESS;

200
}
/** * To list a single user by Id. @return String */
public String edit() {
HttpServletRequest request = (HttpServletRequest) ActionContext.getContext().get(
ServletActionContext.HTTP_REQUEST);
user = userDAO.listUserById(Long.parseLong( request.getParameter("id")));
return SUCCESS;
}
public User getUser() { return user; }
public void setUser(User user) { this.user = user; }
public List<User> getUserList() { return userList; }
public void setUserList(List<User> userList){this.userList = userList; }
}
In the struts configuration file we have four different actions corresponding to the different CRUD
operations. During the save, update and delete operations, we need to update the list of users displayed
below so we redirect the result to the listUser acion.
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<package name="default" extends="hibernate-default">
<action name="saveOrUpdateUser" method="saveOrUpdate" class="com.web.UserAction">
<result name="success" type="redirect">listUser</result>
</action>
<action name="listUser" method="list" class="com.web.UserAction">
<result name="success">/register.jsp</result> </action>
<action name="editUser" method="edit" class="com.web.UserAction">
<result name="success">/register.jsp</result> </action>
<action name="deleteUser" method="delete"class="com.web.UserAction">
<result name="success" type="redirect">listUser</result>
</action>
</package>
</struts>
The hibernate.cfg.xml file contains the following configuration.
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD
3.0//EN""http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class"> org.hsqldb.jdbcDriver </property>
<property name="hibernate.connection.url"> jdbc:hsqldb:hsql://localhost </property>
<property name="hibernate.connection.username">sa</property>
<property name="connection.password"></property>
<property name="connection.pool_size">1</property>

201
<property name="hibernate.dialect"> org.hibernate.dialect.HSQLDialect </property>
<property name="show_sql">true</property>
<property name="hbm2ddl.auto">create</property>
<mapping class="com.domain.User" />
</session-factory> </hibernate-configuration>
The deployment descriptor contains the following configuration.
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/webapp_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
<display-name>Struts2Example19</display-name>
<filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.ng.filter. StrutsPrepareAndExecuteFilter </filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>

In the register.jsp page


<%@ 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">
<%@taglib uri="/struts-tags" prefix="s"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Registration Page</title>
<s:head />
<style type="text/css">
@import url(style.css);
</style>
</head>
<body>
<s:form action="saveOrUpdateUser">
<s:push value="user">

202
<s:hidden name="id" />
<s:textfield name="name" label="User Name" />
<s:radio name="gender" label="Gender"
list="{'Male','Female'}" />
<s:select name="country" list="{'India','USA','UK'}"
headerKey="" headerValue="Select"
label="Select a country" />
<s:textarea name="aboutYou" label="About You" />
<s:checkbox name="mailingList"
label="Would you like to join our mailing list?" />
<s:submit />
</s:push>
</s:form>
<s:if test="userList.size() > 0">
<div class="content">
<table class="userTable" cellpadding="5px">
<tr class="even">
<th>Name</th>
<th>Gender</th>
<th>Country</th>
<th>About You</th>
<th>Mailing List</th>
<th>Edit</th>
<th>Delete</th>
</tr>
<s:iterator value="userList" status="userStatus">
<tr
class="<s:if test="#userStatus.odd == true ">odd</s:if> <s:else>even</s:else>">
<td><s:property value="name" /></td>
<td><s:property value="gender" /></td>
<td><s:property value="country" /></td>
<td><s:property value="aboutYou" /></td>
<td><s:property value="mailingList" /></td>
<td>
<s:url id="editURL" action="editUser">
<s:param name="id" value="%{id}"></s:param>
</s:url>
<s:a href="%{editURL}">Edit</s:a>
</td>
<td>
<s:url id="deleteURL" action="deleteUser">
<s:param name="id" value="%{id}"></s:param>
</s:url>
<s:a href="%{deleteURL}">Delete</s:a>
</td>
</tr>
</s:iterator>
</table>

203
</div>
</s:if>
</body>
</html>
The push tag is used to move the object to the top of the ValueStack. During add operation we will refer
to the model object User exposed by the ModelDriven inteface, in this case the push tag is not
necessary. But during update operation we refer to the JavaBean property user that is returned by the
listUserById() method, now the push tag will be useful, it pushes the User object to the top of the
ValueStack so we need not use the second-level OGNL expression language like user.name to access the
domain object properties.
public String edit() {
HttpServletRequest request = (HttpServletRequest) ActionContext.getContext().get(
ServletActionContext.HTTP_REQUEST);
user = userDAO.listUserById(Long.parseLong(request. getParameter("id")));
return SUCCESS;
}
The url tag is used to create a new URL. Along with the URL we append the id value, this can be done
using the param tab. In the OGNL expression language we use "%{}" as the escape sequence to refer a
value on the ActionContext.
Hibernate
Coherence supports transparent read/write caching of any data source, including databases, web
services, packaged applications and file systems, however, databases are the most common use case. As
shorthand "database" will be used to describe any back-end data source. Effective caches must support
both intensive read-only and read/write operations, and in the case of read/write operations, the cache
and database must be kept fully synchronized. To accomplish this, Coherence supports Read-Through,
Write-Through, Refresh-Ahead and Write-Behind caching
A CacheStore is an application-specific adapter used to connect a cache to a underlying data source. The
CacheStore implementation accesses the data source by using a data access mechanism.The CacheStore
understands how to build a Java object using data retrieved from the data source, map and write an
object to the data source, and erase an object from the data source.
When an application asks the cache for an entry, for example the key X, and X is not already in the
cache, Coherence will automatically delegate to the CacheStore and ask it to load X from the underlying
data source. If X exists in the data source, the CacheStore will load it, return it to Coherence, then
Coherence will place it in the cache for future use and finally will return X to the application code that
requested it. This is called Read-Through caching.
Coherence can handle updates to the data source in two distinct ways, the first being Write-Through. In
this case, when the application updates a piece of data in the cache (that is, calls put(...) to change a
cache entry,) the operation will not complete (that is, the put will not return) until Coherence has gone
through the CacheStore and successfully stored the data to the underlying data source. This does not
improve write performance at all, since you are still dealing with the latency of the write to the data
source. Improving the write performance is the purpose for the Write-Behind Cache functionality.
In the Write-Behind scenario, modified cache entries are asynchronously written to the data source after
a configurable delay, whether after 10 seconds, 20 minutes, a day or even a week or longer. For WriteBehind caching, Coherence maintains a write-behind queue of the data that must be updated in the data
source. When the application updates X in the cache, X is added to the write-behind queue (if it isn't
there already; otherwise, it is replaced), and after the specified write-behind delay Coherence will call
the CacheStore to update the underlying data source with the latest state of X. Note that the writebehind delay is relative to the first of a series of modifications
cache-config>

204
...
<distributed-scheme>
<scheme-name>categories-cache-all-scheme</scheme-name>
<service-name>DistributedCache</service-name>
<backing-map-scheme>
<!-Read-write-backing-map caching scheme.
-->
<read-write-backing-map-scheme>
<scheme-name>categoriesLoaderScheme</scheme-name>
<internal-cache-scheme>
<local-scheme>
<scheme-ref>categories-eviction</scheme-ref>
</local-scheme>
</internal-cache-scheme>
<cachestore-scheme>
<class-scheme>
<class-name>com.demo.cache.coherence.categories.CategoryCacheLoader</class-name>
</class-scheme>
</cachestore-scheme>
<refresh-ahead-factor>0.5</refresh-ahead-factor>
</read-write-backing-map-scheme>
</backing-map-scheme>
<autostart>true</autostart>
</distributed-scheme>
...
<!-Backing map scheme definition used by all the caches that require
expiry eviction policies. -->
<local-scheme>
<scheme-name>categories-eviction</scheme-name>
<expiry-delay>20s</expiry-delay>
</local-scheme>
...
</cache-config>

size limitation and/or

9.7.1 Read-Through/Write-Through versus Cache-Aside


There are two common approaches to the cache-aside pattern in a clustered environment. One involves
checking for a cache miss, then querying the database, populating the cache, and continuing application
processing. This can result in multiple database visits if different application threads perform this
processing at the same time. Alternatively, applications may perform double-checked locking (which
works since the check is atomic with respect to the cache entry). This, however, results in a substantial
amount of overhead on a cache miss or a database update (a clustered lock, additional read, and
clustered unlock - up to 10 additional network hops, or 6-8ms on a typical gigabit Ethernet connection,
plus additional processing overhead and an increase in the "lock duration" for a cache entry).
By using inline caching, the entry is locked only for the 2 network hops (while the data is copied to the
backup server for fault-tolerance). Additionally, the locks are maintained locally on the partition owner.
Furthermore, application code is fully managed on the cache server, meaning that only a controlled
subset of nodes will directly access the database (resulting in more predictable load and security).
Additionally, this decouples cache clients from database logic.
9.7.2 Refresh-Ahead versus Read-Through
Refresh-ahead offers reduced latency compared to read-through, but only if the cache can accurately
predict which cache items are likely to be needed in the future. With full accuracy in these predictions,

205
refresh-ahead will offer reduced latency and no added overhead. The higher the rate of misprediction,
the greater the impact will be on throughput (as more unnecessary requests will be sent to the
database) - potentially even having a negative impact on latency should the database start to fall behind
on request processing.
9.7.3 Write-Behind versus Write-Through
If the requirements for write-behind caching can be satisfied, write-behind caching may deliver
considerably higher throughput and reduced latency compared to write-through caching. Additionally
write-behind caching lowers the load on the database (fewer writes), and on the cache server (reduced
cache value deserialization).
9.8 Idempotency
All CacheStore operations should be designed to be idempotent (that is, repeatable without unwanted
side-effects). For write-through and write-behind caches, this allows Coherence to provide low-cost faulttolerance for partial updates by re-trying the database portion of a cache update during failover
processing. For write-behind caching, idempotency also allows Coherence to combine multiple cache
updates into a single CacheStore invocation without affecting data integrity.
Applications that have a requirement for write-behind caching but which must avoid write-combining (for
example, for auditing reasons), should create a "versioned" cache key (for example, by combining the
natural primary key with a sequence id).
9.9 Write-Through Limitations
Coherence does not support two-phase CacheStore operations across multiple CacheStore instances. In
other words, if two cache entries are updated, triggering calls to CacheStore modules sitting on separate
cache servers, it is possible for one database update to succeed and for the other to fail. In this case, it
may be preferable to use a cache-aside architecture (updating the cache and database as two separate
components of a single transaction) with the application server transaction manager. In many cases it is
possible to design the database schema to prevent logical commit failures (but obviously not server
failures). Write-behind caching avoids this issue as "puts" are not affected by database behavior (and
the underlying issues will have been addressed earlier in the design process). This limitation will be
addressed in an upcoming release of Coherence.
9.10 Cache Queries
Cache queries only operate on data stored in the cache and will not trigger the CacheStore to load any
missing (or potentially missing) data. Therefore, applications that query CacheStore-backed caches
should ensure that all necessary data required for the queries has been pre-loaded. For efficiency, most
bulk load operations should be done at application startup by streaming the dataset directly from the
database into the cache (batching blocks of data into the cache by using NamedCache.putAll(). The
loader process will need to use a "Controllable Cachestore" pattern to disable circular updates back to
the database. The CacheStore may be controlled by using an Invocation service (sending agents across
the cluster to modify a local flag in each JVM) or by setting the value in a Replicated cache (a different
cache service) and reading it in every CacheStore method invocation (minimal overhead compared to the
typical database operation). A custom MBean can also be used, a simple task with Coherence's clustered
JMX facilities.
9.11 Creating a CacheStore Implementation
CacheStore implementations are pluggable, and depending on the cache's usage of the data source you
will need to implement one of two interfaces:

CacheLoader for read-only caches

CacheStore which extends CacheLoader to support read/write caches


These interfaces are located in the com.tangosol.net.cache package. The CacheLoader interface has two
main methods: load(Object key) and loadAll(Collection keys), and the CacheStore interface adds the
methods store(Object key, Object value), storeAll(Map mapEntries), erase(Object key), and
eraseAll(Collection colKeys).
To plug in a CacheStore module, specify the CacheStore implementation class name within the
distributed-scheme, backing-map-scheme, cachestore-scheme, or read-write-backing-map-scheme,
cache configuration element.
The read-write-backing-map-scheme configures a com.tangosol.net.cache.ReadWriteBackingMap. This

206
backing map is composed of two key elements: an internal map that actually caches the data (see
internal-cache-scheme), and a CacheStore module that interacts with the database
<?xml version="1.0"?>
<!DOCTYPE cache-config SYSTEM "cache-config.dtd">
<cache-config>
<caching-scheme-mapping>
<cache-mapping>
<cache-name>com.company.dto.*</cache-name>
<scheme-name>distributed-rwbm</scheme-name>
</cache-mapping>
</caching-scheme-mapping>
<caching-schemes>
<distributed-scheme>
<scheme-name>distributed-rwbm</scheme-name>
<backing-map-scheme>
<read-write-backing-map-scheme>
<internal-cache-scheme>
<local-scheme/>
</internal-cache-scheme>
<cachestore-scheme>
<class-scheme>
<class-name>com.company.MyCacheStore</class-name>
<init-params>
<init-param>
<param-type>java.lang.String</param-type>
<param-value>{cache-name}</param-value>
</init-param>
</init-params>
</class-scheme>
</cachestore-scheme>
</read-write-backing-map-scheme>
</backing-map-scheme>
</distributed-scheme>
</caching-schemes>
</cache-config>
>
Note:
Thread Count: The use of a CacheStore module will substantially increase the consumption of cache
service threads (even the fastest database select is orders of magnitude slower than updating an inmemory structure). Consequently, the cache service thread count will need to be increased (typically in
the range 10-100). The most noticeable symptom of an insufficient thread pool is increased latency for
cache requests (without corresponding behavior in the backing database).
9.13.1 Re-entrant Calls
The CacheStore implementation must not call back into the hosting cache service. This includes OR/M
solutions that may internally reference Coherence cache services. Note that calling into another cache
service instance is allowed, though care should be taken to avoid deeply nested calls (as each call will
"consume" a cache service thread and could result in deadlock if a cache service threadpool is
exhausted).

207
9.13.2 Cache Server Classpath
The classes for cache entries (also known as Value Objects, Data Transfer Objects, and so on) must be
in the cache server classpath (as the cache server must serialize-deserialize cache entries to interact with
the CacheStore module.
9.13.3 CacheStore Collection Operations
The CacheStore.storeAll() method is most likely to be used if the cache is configured as write-behind and
the <write-batch-factor> is configured. The CacheStore.loadAll() method is not currently used by
Coherence. For similar reasons, its first use will likely require refresh-ahead to be enabled.
9.13.4 Connection Pools
Database connections should be retrieved from the container connection pool (or a 3rd party connection
pool) or by using a thread-local lazy-initialization pattern. As dedicated cache servers are often deployed
without a managing container, the latter may be the most attractive option (though the cache service
thread-pool size should be constrained to avoid excessive simultaneous database connections).
save vs saveOrUpdate() vs persisit
session.save() : Save does an insert and will fail if the primary key is already persistent.
session.saveOrUpdate() : saveOrUpdate does a select first to determine if it needs to do an insert or an
update.
Insert data if primary key not exist otherwise update data.
session.persist() : Does the same like session.save().
But session.save() return Serializable object but session.persist() return void.
session.save() returns the generated identifier (Serializable object) and session.persist() doesn't.
Hibernate vs JDBC
There are so many
1) Hibernate is data base independent, your code will work for all ORACLE,MySQL ,SQLServer etc.
In case of JDBC query must be data base specific.
2) As Hibernate is set of Objects , you don?t need to learn SQL language.
You can treat TABLE as a Object . Only Java knowledge is need.
In case of JDBC you need to learn SQL.
3) Don?t need Query tuning in case of Hibernate. If you use Criteria Quires in Hibernate then hibernate
automatically tuned your query and return best result with performance.
In case of JDBC you need to tune your queries.
4) You will get benefit of Cache. Hibernate support two level of cache. First level and 2nd level. So you
can store your data into Cache for better performance.
In case of JDBC you need to implement your java cache .
5) Hibernate supports Query cache and It will provide the statistics about your query and database
status.
JDBC Not provides any statistics.
6) Development fast in case of Hibernate because you don?t need to write queries
7) No need to create any connection pool in case of Hibernate. You can use c3p0.
In case of JDBC you need to write your own connection pool
8) In the xml file you can see all the relations between tables in case of Hibernate. Easy readability.

208

9) You can load your objects on start up using lazy=false in case of Hibernate.
JDBC Don?t have such support.
10 ) Hibernate Supports automatic versioning of rows but JDBC Not.
Lazy Fetching
Lazy fetching decides whether to load child objects while loading the Parent Object.
You need to do this setting respective hibernate mapping file of the parent class.
Lazy = true (means not to load child)
By default the lazy loading of the child objects is true.
This make sure that the child objects are not loaded unless they are explicitly invoked in the application
by calling getChild() method on parent.In this case hibernate issues a fresh database call to load the
child when getChild() is actully called on the Parent object
.But in some cases you do need to load the child objects when parent is loaded.
Just make the lazy=false and hibernate will load the child when parent is loaded from the database.
Example :
If you have a TABLE ? EMPLOYEE mapped to Employee object and contains set of Address objects.
Parent Class : Employee class
Child class : Address Class
public class Employee {
private Set address = new HashSet(); // contains set of child Address objects
public Set getAddress () {
return address;
}
public void setAddresss(Set address) {
this. address = address;
}
}
In the Employee.hbm.xml file
<set name="address" inverse="true" cascade="delete" lazy="false">
<key column="a_id" />
<one-to-many class="beans Address"/>
</set>
In the above configuration.
If lazy="false" : - when you load the Employee object that time child object Adress is also loaded and set
to setAddresss() method.
If you call employee.getAdress() then loaded data returns.No fresh database call.
If lazy="true" :- This the default configuration. If you don?t mention then hibernate consider lazy=true.
when you load the Employee object that time child object Adress is not loaded. You need extra call to
data base to get address objects.
If you call employee.getAdress() then that time database query fires and return results. Fresh database
call.
PREVENT CONCURRENT UPDATE IN HBM
version checking used in hibernate when more then one thread trying to access same data.
For example :
User A edit the row of the TABLE for update ( In the User Interface changing data - This is user thinking
time)
and in the same time User B edit the same record for update and click the update.

209
Then User A click the Update and update done. Chnage made by user B is gone.
In hibernate you can perevent slate object updatation using version checking.
Check the version of the row when you are upding the row.
Get the version of the row when you are fetching the row of the TABLE for update.
On the time of updation just fetch the version number and match with your version number ( on the
time of fetching).
This way you can prevent slate object updatation.
Steps 1:
Declare a variable "versionId" in your Class with setter and getter.
public class Campign {
private Long versionId;
private Long campignId;
private String name;
public Long getVersionId() {
return versionId;
}
public void setVersionId(Long versionId) {
this.versionId = versionId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Long getCampignId() {
return campignId;
}
private void setCampignId(Long campignId) {
this.campignId = campignId;
}
}
Step 2.
In the .hbm.xml file
<class name="beans.Campign" table="CAMPIGN" optimistic-lock="version">
<id name="campignId" type="long" column="cid">
<generator class="sequence">
<param name="sequence">CAMPIGN_ID_SEQ</param>
</generator>
</id>
<version name="versionId" type="long" column="version" />
<property name="name" column="c_name"/>

210

</class>
Step 3.
Create a coulmn name "version" in the CAMPIGN table.
Step 4.
In the code
// foo is an instance loaded by a previous Session
session = sf.openSession();
int oldVersion = foo.getVersion();
session.load( foo, foo.getKey() );
if ( oldVersion!=foo.getVersion ) throw new StaleObjectStateException();
foo.setProperty("bar");
session.flush();
session.connection().commit();
session.close();
You can handle StaleObjectStateException() and do what ever you want.
You can display error message.
Hibernate autumatically create/update the version number when you update/insert any row in the table.
saveorUpdate vs session.merge
<b>saveOrUpdate() </b>does the following:
? if the object is already persistent in this session, do nothing
? if another object associated with the session has the same identifier, throw an exception
? if the object has no identifier property, save() it
? if the object's identifier has the value assigned to a newly instantiated object, save() it
? if the object is versioned (by a <version> or <timestamp>), and the version property value is the
same
value assigned to a newly instantiated object, save() it otherwise update() the object
<b>merge() </b>is very different: if there is a persistent instance with the same identifier currently
associated with the session, copy the state of the given object onto the persistent instance
if there is no persistent instance currently associated with the session, try to load it from the database,
or create a new persistent instance the persistent instance is returned the given instance does not
become associated with the session, it remains detached
spring with hibernate
Step 1. In the struts-config.xml add plugin
<plug-in className="org.springframework.web.struts.ContextLoaderPlugIn">
<set-property property="contextConfigLocation"
value="/WEB-INF/applicationContext.xml"/>
</plug-in>
Step 2. In the applicationContext.xml file Configure datasourse
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName"><value>oracle.jdbc.driver.OracleDriver</value>
</property>
<property name="url"><value>jdbc:oracle:thin:@10.10.01.24:1541:ebizd</value>
</property>

211
<property name="username"><value>sa</value></property>
<property name="password"><value></value></property>
</bean>
Step 3. Configure SessionFactory
<!-- Hibernate SessionFactory -->
<bean id="sessionFactory" class="org.springframework.orm.hibernate.LocalSessionFactoryBean">
<property name="dataSource"><ref local="dataSource"/></property>
<property name="mappingResources">
<list>
<value>com/test/dbxml/User.hbm.xml</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">net.sf.hibernate.dialect.OracleDialect </prop>
</props>
</property> </bean>
Step 4. Configure User.hbm.xml
<hibernate-mapping>
<class name="org.test.model.User" table="app_user">
<id name="id" column="id" >
<generator class="increment"/>
</id>
<property name="firstName" column="first_name" not-null="true"/>
<property name="lastName" column="last_name" not-null="true"/>
</class>
</hibernate-mapping>
Step 5. In the applicationContext.xml ? configure for DAO
<bean id="userDAO" class="org.test.dao.hibernate.UserDAOHibernate">
<property name="sessionFactory"><ref local="sessionFactory"/></property>
</bean>
Step 6. DAO Class
public class UserDAOHibernate extends HibernateDaoSupport implements UserDAO {
private static Log log = LogFactory.getLog(UserDAOHibernate.class);
public List getUsers() {
return getHibernateTemplate().find("from User");
}
public User getUser(Long id) {
return (User) getHibernateTemplate().get(User.class, id);
}
public void saveUser(User user) {
getHibernateTemplate().saveOrUpdate(user);
if (log.isDebugEnabled()) {
log.debug("userId set to: " + user.getId());
}
}
public void removeUser(Long id) {
Object user = getHibernateTemplate().load(User.class, id);
getHibernateTemplate().delete(user);
}

212
}
Jdbc into hibernate : User Session.connection() method to get JDBC Connection.
Best Practices
1.You must have a default no-argument constructor for your persistent classes and there should be
getXXX() (i.e accessor/getter) and setXXX( i.e. mutator/setter) methods for all your persistable instance
variables.
2.You should implement the equals() and hashCode() methods based on your business key and it is
important not to use the id field in your equals() and hashCode() definition if the id field is a surrogate
key (i.e. Hibernate managed identifier). This is because the Hibernate only generates and sets the field
when saving the object.
3. It is recommended to implement the Serializable interface. This is potentially useful if you want to
migrate around a multi-processor cluster.
4.The persistent class should not be final because if it is final then lazy loading cannot be used by
creating proxy objects.
Transaction with Plain JDBC in hibernate
If you don't have JTA and don't want to deploy it along with your application, you will usually have to fall
back to JDBC transaction demarcation. Instead of calling the JDBC API you better use Hibernate's
Transaction and the built-in session-per-request functionality:
To enable the thread-bound strategy in your Hibernate configuration:
set hibernate.transaction.factory_class to org.hibernate.transaction.JDBCTransactionFactory
set hibernate.current_session_context_class to thread
Session session = factory.openSession();
Transaction tx = null;
try {
tx = session.beginTransaction();
// Do some work
session.load(...);
session.persist(...);
tx.commit(); // Flush happens automatically
}
catch (RuntimeException e) {
tx.rollback();
throw e; // or display error message
}
finally {
session.close();
}
Session.Update vs session.Lock

213
Both of these methods and saveOrUpdate() method are intended for reattaching a detached object.
The session.lock() method simply reattaches the object to the session without checking or updating the
database on the assumption that the database in sync with the detached object.
It is the best practice to use either session.update(..) or session.saveOrUpdate().
Use session.lock() only if you are absolutely sure that the
detached object is in sync with your detached object or if it does not matter because
you will be overwriting all the columns that would have changed later on within the same transaction.
Each interaction with the persistent store occurs in a new Session. However, the same persistent
instances are reused for each interaction with the database. The application manipulates the state of
detached instances originally loaded in another Session and then "reassociates" them using
Session.update() or Session.saveOrUpdate().
// foo is an instance loaded by a previous Session
foo.setProperty("bar");
session = factory.openSession();
session.saveOrUpdate(foo);
session.flush();
session.connection().commit();
session.close();
You may also call lock() instead of update() and use LockMode.READ (performing a version check,
bypassing all caches) if you are sure that the object has not been modified.
Filter in hibernate
Filter in Hibernate -----USER ( ID INT, USERNAME VARCHAR, ACTIVATED BOOLEAN) - TABLE
public class User {
private int id;
private String username;
private boolean activated;
public boolean isActivated() {
return activated;
} public void setActivated(boolean activated) {
this.activated = activated;
} public int getId() {
return id;
} public void setId(int id) {
this.id = id;
} public String getUsername() {
return username;
} public void setUsername(String username) {
this.username = username;
}
}
----------------------------------------------------------------<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

214
<hibernate-mapping>
<class name="User">
<id name="id" type="int">
<generator class="native"/>
</id>
<property name="username" type="string" length="32"/>
<property name="activated" type="boolean"/>
<filter name="activatedFilter" condition=":activatedParam = activated"/>
</class>

<filter-def name="activatedFilter">
<filter-param name="activatedParam" type="boolean"/>
</filter-def>
</hibernate-mapping>
-------------------------------------------------------------------Save and Fetch using filter example
User user1 = new User();
user1.setUsername("name1");
user1.setActivated(false);
session.save(user1);
User user2 = new User();
user2.setUsername("name2");
user2.setActivated(true);
session.save(user2);
User user3 = new User();
user3.setUsername("name3");
user3.setActivated(true);
session.save(user3);
User user4 = new User();
user4.setUsername("name4");
user4.setActivated(false);
session.save(user4);
All the four user saved to Data Base User Table.
Now Fetch the User using Filter..
Filter filter = session.enableFilter("activatedFilter");
filter.setParameter("activatedParam",new Boolean(true));
Query query = session.createQuery("from User");
Iterator results = query.iterate();
while (results.hasNext()) {
User user = (User) results.next();
System.out.print(user.getUsername() + " is ");
}

215
Guess the Result :
name2 name3
Because Filer is filtering ( only true value) data before query execute.
getCurrentsession() and openSession()
getCurrentSession() :
The "current session" refers to a Hibernate Session bound by Hibernate behind the scenes, to the
transaction scope. A Session is opened when getCurrentSession() is called for the first time and closed
when the transaction ends. It is also flushed automatically before the transaction commits. You can call
getCurrentSession() as often and anywhere you want as long as the transaction runs.
To enable this strategy in your Hibernate configuration:
set hibernate.transaction.manager_lookup_class to a lookup strategy for your JEE container
set hibernate.transaction.factory_class to org.hibernate.transaction.JTATransactionFactory
Only the Session that you obtained with sf.getCurrentSession() is flushed and closed automatically.
Example :
try {
UserTransaction tx = (UserTransaction)new InitialContext()
.lookup("java:comp/UserTransaction");
tx.begin();
// Do some work
sf.getCurrentSession().createQuery(...);
sf.getCurrentSession().persist(...);
tx.commit();
} catch (RuntimeException e) {
tx.rollback();
throw e; // or display error message
}
openSession() :
If you decide to use manage the Session yourself the go for sf.openSession() , you have to flush() and
close() it.
It does not flush and close() automatically.
Example :
UserTransaction tx = (UserTransaction)new InitialContext()
.lookup("java:comp/UserTransaction");
Session session = factory.openSession();
try {
tx.begin();
// Do some work
session.createQuery(...);
session.persist(...);
session.flush(); // Extra work you need to do

216
tx.commit();
}
catch (RuntimeException e) {
tx.rollback();
throw e; // or display error message
}
finally {
session.close(); // Extra work you need to do
}
value replacement in message resource
In the resource bundle file, you can define a template like:
errors.required={0} is required.
ActionErrors errors = new ActionErrors();
errors.add(ActionErrors.GLOBAL_ERROR,
new ActionError("error.custform","First Name"));
Then the Error message is : First Name is required.
Other constructors are
public ActionError(String key, Object value0, Object value1)
...
public ActionError(String key, Object[] values);
load() will throw an unrecoverable exception if there is no matching database row.
get() will return null if there is no matching database row.
criteria query 2 condition
<class name="com.bean.Organization" table="ORGANIZATION">
<id name="orgId" column="ORG_ID" type="long">
<generator class="native"/>
</id>
<property name="organizationName" column="ORGANISATION_NAME" type="string" length="500"/>
<property name="town" column="TOWN" type="string" length="200"/>
<property name="statusCode" column="STATUS" type="string" length="1"/>
</class>
List of organisation where town equals to pune and status = "A".
List organizationList = session.createCriteria(Organization.class)
.add(Restrictions.eq("town","pune"))
.add(Restrictions.eq("statusCode","A"))
.list();
share session with different threads
Session is a light weight and a non-threadsafe object (No, you cannot share it between threads) that
represents a single unit-of-work with the database. Sessions are opened by a SessionFactory and then
are closed when all work is complete. Session is the primary interface for the persistence service. A
session obtains a database connection lazily (i.e. only when required). To avoid creating too many
sessions ThreadLocal class can be used as shown below to get the current session no matter how many
times you make call to the currentSession() method.

217

public class HibernateUtil {


public static final ThreadLocal local = new ThreadLocal();
public static Session currentSession() throws HibernateException {
Session session = (Session) local.get();
//open a new session if this thread has no session
if(session == null) {
session = sessionFactory.openSession();
local.set(session);
}
return session;
}
}
generate Primary key
<id name="userId" column="USER_ID" type="int">
<generator class="increment"/>
</id>
increment generator class automatically generate the primary key for you.
STRUTS WITH SPRING INTEGRATION
Integrate Spring and Struts 2 using the struts2-spring-plugin.\
First add the org.springframework.web.context.ContextLoaderListener to the web.xml file.
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/webapp_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
<display-name>Struts2Example14</display-name>
<filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.ng.filter. StrutsPrepareAndExecuteFilter</filter-class>
</filter>
<listener>
<listener-class>org.springframework.web.context. ContextLoaderListener</listener-class>
</listener>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>

218

By default the applicationContext.xml file will be used


<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/springbeans.dtd">
<beans>
<bean id="helloWorldClass" class="com.HelloWorld" >
<property name="message" value="Hello World!" />
</bean>
</beans>
struts.xml
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<package name="default" extends="struts-default">
<action name="helloWorld" class="helloWorldClass">
<result name="SUCCESS">/success.jsp</result>
</action>
</package>
</struts>
The only change here is instead of referring the com.HelloWorld class directly, we relate it using the
bean name given in the spring bean configuration file.
In the execute() method we simply return "SUCCESS" and the message attribute is set using setter
injection.
package com;
public class HelloWorld {
private String message;
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public String execute() {
return "SUCCESS";
}
}
<META HTTP-EQUIV="Refresh" CONTENT="0;URL=helloWorld.action">
After invoking the execute() method the user will be directed to the success.jsp page.

STRUTS SPRING HIBERNATE INTEGRATION.

219

DB
CREATE TABLE `login` ( `id` int(11) NOT NULL default '0', `loginid` varchar(20) NOT NULL default '',
`password` varchar(20) NOT NULL default '', `email` varchar(30) default NULL, `address` varchar(60)
default NULL, `phno` int(11) default '0', PRIMARY KEY (`id`), UNIQUE KEY `loginid` (`loginid`) )
TYPE=MyISAM;
jdbc.properties
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://192.168.10.3:3306/strutshibernatespring
jdbc.username=deepak
jdbc.password=deepak
Create an directory "libext" under "project\WEB-INF\". This directory will be used in our project to place
the library files that which will used to compile the java classes. For compiling Servlets we need the
Servlet, so you find "servlet-api.jar" from you tomcat server and copy in "libext" directory.
build.xml file you can change the jar file name for your application by changing the following value:
<property name="project.jar.file" value="project.jar"/>
Hibernate Part
Hibernate Mapping Class
only one table in database, need one POJO class and the hibernate mapping file to map the login object
to the database table. Here is the code for "Login.hbm.xml" mapping file:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping auto-import="true" default-lazy="false">
<class name="dao.hibernate.Login" table="login" >
<id name="id"
type="java.lang.Integer"
column="id"
>
<generator class="increment" />
</id>
<property name="loginid" type="java.lang.String"
column="loginid"
not-null="true"
unique="true"
length="20"
/>
<property
name="password"
type="java.lang.String"
column="password"

220
not-null="true"
length="20"
/>
<property
name="email"
type="java.lang.String"
column="email"
not-null="false"
length="30"
/>
<property
name="address"
type="java.lang.String"
column="address"
not-null="false"
length="60"
/>
<property
name="phno"
type="int"
column="phno"
not-null="false"
length="11"
/>
</class>
</hibernate-mapping>
POJO Class
package dao.hibernate;
import java.io.Serializable;
public class Login implements Serializable {
private Integer id;
private String loginid;
private String password;
private String email;
private String address;
private int phno;
public Login(Integer id, String loginid, String password, String email,
String address, int phno) {
this.id = id;
this.loginid = loginid;
this.password = password;
this.address = address;
this.phno = phno;
this.email = email;
}

221

public Login() {
}
public Integer getId() {
return this.id;
}
public void setId(Integer id) {
this.id = id;
}
public String getLoginid() {
return this.loginid;
}
public void setLoginid(String loginid) {
this.loginid = loginid;
}
public String getPassword() {
return this.password;
}
public void setPassword(String password) {
this.password = password;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public int getPhno() {
return phno;
}
public void setPhno(int phno) {
this.phno = phno;
}
}

222
ApplicationContext.xml
An ApplicationContext is the central interface to provide configuration for an application.
Functionalities:

Bean factory methods, inherited from ListableBeanFactory. This avoids the need for applications
to use singletons.
The ability to resolve messages, supporting internationalization. Inherited from the
MessageSource interface.
The ability to load file resources in a generic fashion. Inherited from the ResourceLoader interface.
The ability to publish events. Implementations must provide a means of registering event
listeners.
Inheritance from a parent context. Definitions in a descendant context will always take priority. for
example, a single parent context can be used by an entire web application, while each servlet has
its own child context that is independent of that of any other servlet.
Here is the code of our applicationContext-hibernate.xml file:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/springbeans.dtd">
<beans>
<bean id="propertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location"><value>/WEB-INF/jdbc.properties</value></property>
</bean>
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName"><value>${jdbc.driverClassName}</value></property>
<property name="url"><value>${jdbc.url}</value></property>
<property name="username"><value>${jdbc.username}</value></property>
<property name="password"><value>${jdbc.password}</value></property>
</bean>
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource"><ref local="dataSource"/></property>
<property name="mappingResources">
<list>
<value>/dao/hibernate/Login.hbm.xml</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">${hibernate.dialect}</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
<bean id="transactionManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory"><ref local="sessionFactory"/></property>
</bean>

223

<bean id="HibernateSpringDaoTarget" class="dao.SpringHibernateDAOImpl">


<property name="sessionFactory"><ref local="sessionFactory"/></property>
</bean>
- Transactional proxy for Login Application central data access object.
- Defines specific transaction attributes with "readOnly" markers,
- which is an optimization that is particularly valuable with Hibernate
(to suppress unnecessary flush attempts for read-only operations).
<bean id="SpringHibernateDao"
class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean">
<property name="transactionManager"><ref local="transactionManager"/></property>
<property name="target"><ref local="HibernateSpringDaoTarget"/></property>
<property name="transactionAttributes">
<props>
<prop key="get*">PROPAGATION_REQUIRED,readOnly</prop>
<prop key="find*">PROPAGATION_REQUIRED,readOnly</prop>
<prop key="load*">PROPAGATION_REQUIRED,readOnly</prop>
<prop key="store*">PROPAGATION_REQUIRED</prop>
</props>
</property>
</bean>
<bean id="mailbean" class="web.common.SendMail">
<property name="strSmtp"><value>192.168.10.14</value></property>
</bean>
</beans>
Understanding the applicationContext-hibernate.xml configuration file
Data source configuration:
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName"><value>${jdbc.driverClassName}</value></property>
<property name="url"><value>${jdbc.url}</value></property>
<property name="username"><value>${jdbc.username}</value></property>
<property name="password"><value>${jdbc.password}</value></property>
</bean>
The values for ${jdbc.driverClassName}, ${jdbc.url}, ${jdbc.username} and ${jdbc.password} are
defined in the jdbc.properties file which is present in the /WEB-INF/ directory of the web application.
Hibernate Session Factory:
<!-- Hibernate SessionFactory -->
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource"><ref local="dataSource"/></property>
<property name="mappingResources">
<list>
<value>/dao/hibernate/Login.hbm.xml</value>
</list>

224
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">${hibernate.dialect}</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
Configuring the Transaction Proxy for the DAO
<bean id="SpringHibernateDao"
class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean">
<property name="transactionManager"><ref local="transactionManager"/></property>
<property name="target"><ref local="HibernateSpringDaoTarget"/></property>
<property name="transactionAttributes">
<props>
<prop key="get*">PROPAGATION_REQUIRED,readOnly</prop>
<prop key="find*">PROPAGATION_REQUIRED,readOnly</prop>
<prop key="load*">PROPAGATION_REQUIRED,readOnly</prop>
<prop key="store*">PROPAGATION_REQUIRED</prop>
</props>
</property>
</bean>
Mailer Bean
<bean id="mailbean" class="web.common.SendMail">
<property name="strSmtp"><value>192.168.10.14</value></property>
</bean>
Context Loader Servlet start up Spring's root WebApplicationContext when web application is
loaded.
This class has been deprecated for containers implementing Servlet API 2.4 or higher, in favor of
ContextLoaderListener. According to Servlet 2.4, listeners must be initialized before load-on-startup
servlets. Many Servlet 2.3 containers already enforce this behavior. If you use such a container, this
servlet can be replaced with ContextLoaderListener. Else or if working with a Servlet 2.2 container, stick
with this servlet.
Modification in the web.xml file
<servlet>
<servlet-name>context</servlet-name>
<servlet-class>
org.springframework.web.context.ContextLoaderServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/applicationContext-hibernate.x
ml</param-value>
</context-param>
Here is the full content of our web.xml file:
<?xml version="1.0" encoding="ISO-8859-1"?>

225
<!DOCTYPE web-app
PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.2//EN"
"http://java.sun.com/j2ee/dtds/web-app_2_2.dtd">
<web-app>
<display-name>Struts Blank Application</display-name>
<context-param>
<param-name>log4jConfigLocation</param-name>
<param-value>/WEB-INF/log4j.properties
</param-value>
</context-param>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/applicationContext-hibernate.xml
</param-value>
</context-param>
<servlet>
<servlet-name>context</servlet-name>
<servlet-class>
org.springframework.web.context.ContextLoaderServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet>
<servlet-name>action</servlet-name>
<servlet-class>org.apache.struts.action.ActionServlet
</servlet-class>
<init-param>
<param-name>config</param-name>
<param-value>/WEB-INF/struts-config.xml</param-value>
</init-param>
<init-param>
<param-name>debug</param-name>
<param-value>2</param-value>
</init-param>
<init-param>
<param-name>detail</param-name>
<param-value>2</param-value>
</init-param>
<load-on-startup>2</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>action</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>

226

<welcome-file-list><welcome-file>index.jsp</welcome-file></welcome-file-list>
<taglib>
<taglib-uri>/tags/struts-bean</taglib-uri>
<taglib-location>/WEB-INF/struts-bean.tld</taglib-location>
</taglib>
<taglib>
<taglib-uri>/tags/struts-html</taglib-uri>
<taglib-location>/WEB-INF/struts-html.tld</taglib-location>
</taglib>
<taglib>
<taglib-uri>/tags/struts-logic</taglib-uri>
<taglib-location>/WEB-INF/struts-logic.tld</taglib-location>
</taglib>
<taglib>
<taglib-uri>/tags/struts-nested</taglib-uri>
<taglib-location>/WEB-INF/struts-nested.tld</taglib-location>
</taglib>
<taglib>
<taglib-uri>/tags/struts-tiles</taglib-uri>
<taglib-location>/WEB-INF/struts-tiles.tld</taglib-location>
</taglib>
</web-app>

Understanding Spring Struts Hibernate DAO Layer

The Data Access Object for this application is written using hibernate framework. Hibernate is a
collection of libraries and xml file used for mapping object oriented domain model to a relational
database. It is a Open Source available for object relation database mapping written in java. It offers
facilities such as connection pooling, transaction management, updating, insertion and deletion of data
very easily.
In hibernate application separate class is used to represent table in the database. Each table
have their corresponding class hibernate and mapping are done with the help of .hbm.xml file. Each field
of the table is mapped with .hbm.xml file. An example of Login.hbm.xml is given below with their class.

Login.java
package dao;
import java.io.Serializable;
public class Login implements Serializable {

227
private Integer id;
private String loginid;
private String password;
public Login() {
}
public Login(Integer id, String loginid, String password) {
this.id = id;
this.loginid = loginid;
this.password = password;
}
public Integer getId() {
return id;
} public void setId(Integer id) {
this.id = id;
}public String getLoginid() {
return loginid;
} public void setLoginid(String loginid) {
this.loginid = loginid;
} public String getPassword() {
return password;
} public void setPassword(String password) {
this.password = password;
}
}
Login.hbm.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping auto-import="true" default-lazy="false">
<class name="dao.hibernate.Login" table="login">
<id name="id" type="java.lang.Integer" column="id">
<generator class="increment" />
</id>
<property name="loginid" type="java.lang.String" column="loginid" not-null="true" unique="true"
length="20" />
<property name="password" type="java.lang.String" column="password" not-null="true" length="20">
<property name="email" type="java.lang.String" column="email" not-null="false" length="30" />
<property name="address" type="java.lang.String" column="address" not-null="false" length="60" />
<property name="phno" type="int" column="phno" not-null="false" length="11" />
</class>
</hibernate-mapping>
The Hibernate DAO consists applicationContext-hibernate.xml file, which holds the all the
information related to database connection, such as connection URL, database driver, user name,
password, size of connection pool, location of .hbm file etc. Please consider the simple

228
applicationContext-hibernate.xml file is given below-

applicationContext-hibernate.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/springbeans.dtd">
<beans>
<bean id="propertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location">
<value>/WEB-INF/jdbc.properties</value>
</property>
</bean>
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName">
<value>${jdbc.driverClassName}</value>
</property>
<property name="url">
<value>${jdbc.url}</value>
</property>
<property name="username">
<value>${jdbc.username}</value>
</property>
<property name="password">
<value>${jdbc.password}</value>
</property>
</bean>
</beans>
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource">
<ref local="dataSource" />
</property>
<property name="mappingResources">
<list>
<value>/dao/hibernate/Login.hbm.xml</value>
</list>
</property>

229
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">${hibernate.dialect}</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>

ApplicationDao.java
public class SpringHibernateDAOImpl extends HibernateDaoSupport {
public boolean checkUserLogin(String strUserName, String strPassword)
throws DataAccessException, java.sql.SQLException {
boolean valid = false;
Connection conn = this.getSession().connection();
Statement smt = conn.createStatement();
ResultSet rs;
String query = "select id from login where loginid='" + strUserName + "' and password='" +
strPassword + "'";
rs = smt.executeQuery(query);
if (rs.next() == true) {
valid = true;
} else {
valid = false;
}
smt.close();
rs.close();
conn.close();
return valid;
}
}
DAO Layer Explained
DAO stand for Data Access Object, it is design pattern. The DAO contains a connection to a database
and basic operation on the database. The other layer of the application can interact with the database by
making an object of DAO class and calling their required method only. It is an important part of the
application. It completely hides the data access logic / code from other part of the application. The user
/ developer can only access their code through their API.
Data Access Object is a technique which separate the data access logic and object persistence. It also
provides the flexibility to change application prospective without effecting rest of the part of the
application. It provides a very simple and consistence API. Because of its simplicity it has become a
mandatory parts of a web application.

230

Data Access Object

The DAO centralize all the operation on the database.


In the present project the DAO class gets connection from the connection factory class (It holds a
connection). The bean class gives the data on which operation is performed. Finally DAO class performs
the operation on the database and returns the response to the other layer of the application. The
internal processing of Data Access Object is given below.

DAO Internal Processing

One of the great advantage of DAO is the, you do not require to write a code for database connection on
every where, you just make an object of DAO class and call the required method to perform operation
on database.

231
One of the great advantage of DAO is the, you do not require to write a code for database connection on
every where, you just make an object of DAO class and call the required method to perform operation
on database.

In our application we have developed mailer bean that sends welcome email when a new user is
registered to the system. Mail Bean also used when user asks for the forgotten password.

package web.common;
import javax.mail.*;
import javax.mail.internet.*;
import java.util.*;
public class SendMail {
private String strSmtp;
public void setStrSmtp(String strSmtp){
this.strSmtp=strSmtp;
} public String getStrSmtp() {
return this.strSmtp;
} public void sendMail( String recipients[ ], String subject, String message,String from)
throws MessagingException {
boolean debug = false;
Properties props = new Properties();
props.put("mail.smtp.host", getStrSmtp());
Session session = Session.getDefaultInstance(props, null);
session.setDebug(debug);
Message msg = new MimeMessage(session);
InternetAddress addressFrom = new InternetAddress(from);
msg.setFrom(addressFrom);
InternetAddress[] addressTo = new
InternetAddress[recipients.length];
for (int i = 0; i < recipients.length; i++)
{
addressTo[i] = new InternetAddress(recipients[i]);
}
msg.setRecipients(Message.RecipientType.TO, addressTo);
//msg.addHeader("MyHeaderName", "myHeaderValue");
msg.setSubject(subject);
msg.setContent(message, "text/plain");
Transport.send(msg);
}
}

Declare a member variable 'strSmtp' to store name of the mail server for the connection. This strSmtp
represents the host name or IP address of mail server. use setter and getter methods to set or get the
value of strSmtp. After getting the value of strSmtp,set this value into a property object.
Properties props = new Properties();

232
props.put("mail.smtp.host", getStrSmtp());

The property 'mail.smtp.host' contains the information about mail server to be used for the connection.
Now this is time to connect with mail server and create a session. This is done by a specific class of Java
Mail API named Session.
Session session = Session.getDefaultInstance(props, null);
session.setDebug(debug);

Create a Message from the Session. This Message class represents the email message. Message class is
an abstract class, so you must create an instance of a subclass. That subclass is Mime Message.
Message msg = new MimeMessage(session);

Create a instances of InternetAddress class for from and to email addresses.


InternetAddress addressFrom = new InternetAddress(from);
InternetAddress[] addressTo = new InternetAddress[recipients.length];
for (int i = 0; i < recipients.length; i++) {
addressTo[i] = new InternetAddress(recipients[i]);
}

setFrom() and setRecipients() methods of Message class set from and recipients email addresses
msg.setFrom(addressFrom);
msg.setRecipients(Message.RecipientType.TO, addressTo);
Now, we will set subject of message and content type.
msg.setSubject(subject);
msg.setContent(message, "text/plain");

send msg with the Transport class


Transport.send(msg);

This uses the SMTP server specified in the properties for the session.

233

Now set this bean and property in applicationContext.xml file


<beans>
<bean id="mailbean" class="web.common.SendMail">
<property name="strSmtp"><value>192.168.10.14</value></property>
</bean>
</beans>

Here we set the host name or IP of webserver.

package web.common;
public class ProjectConstants {
public static String MAIL_BEAN="mailbean";
public static String FROM_MAIL="deepak@localhost";
}

web.common.SendMail mailBean = (web.common.SendMail)


ServiceFinder.getContext(request).getBean(web.common.ProjectConstants.MAIL_BEAN);
String subject="Your username & password ";
String message="Hi,"+username;

message+="\n
message+="\n
message+="\n
message+="\n
message+="\n

Your username is "+username+".";


Your password is "+strPasswordEmail[0]+".";
Please login to the web site with your username and password.";
\n Thanks";
\n \n Regards";

String from=web.common.ProjectConstants.FROM_MAIL;
try{
mailBean.sendMail(reciepent,subject,message,from);
}
catch(Exception e){
System.out.println("Error in sending mail:"+e);
}

234
This User Registration section of application is composed of two Views.
1. Registration Form: Registration Form displays the fields to take the necessary input from the user.
2. Result Page: The result page displays the message that indicates success. If the there is some error
while registering the user, Registration Form is displayed again indicating the error occurred during the
registration process.
Registration JSP (userRegister.jsp)
The Registration JSP (userRegister.jsp) generates the registration form and displayed to the user to take
the input.
userRegister.jsp
<%@ taglib uri="/tags/struts-bean" prefix="bean" %>
<%@ taglib uri="/tags/struts-html" prefix="html" %>
<html:html locale="true">
<head>
<LINK rel="stylesheet" type="text/css" name="anyname" href="<html:rewrite
page='/css/style.css'/>">
<title></title>
<html:base/>
<SCRIPT LANGUAGE=javascript>
function checkEmail(email) {
if (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(email)){
return (true)
}
alert("Invalid E-mail Address! Please re-enter.")
return (false);
}
function validateForm(formObj){
if(formObj.userid.value.length==0){
alert("Please enter User ID!");
formObj.userid.focus();
return false;
}
if(formObj.password.value.length==0){
alert("Please enter password!");
formObj.password.focus();
return false;
}
if(formObj.email.value.length==0){
alert("Please enter Email!");
formObj.email.focus();
return false;
}
if(!checkEmail(formObj.email.value)){
formObj.email.focus();
return false;
}

235
if(formObj.address.value.length==0){
alert("Please enter address!");
formObj.address.focus();
return false;
}
if(formObj.phno.value.length==0){
alert("Please enter Phone No.!");
formObj.phno.focus();
return false;
}
if(isNaN(formObj.phno.value)){
alert("Please enter correct Phone No!");
formObj.phno.focus();
return false;
}
formObj.actionUpdateData.value="update";
return true;
}
</SCRIPT>
</head>
<body>
<%@ include file="../top.jsp"%>
<center>
<!-<table width="60%">
<tr>
<td width="100%">
-->
<html:form action="/userregister"
method="post" onsubmit="return validateForm(this);">
<html:hidden property="id" />
<html:hidden property="action"/>
<html:hidden property="actionUpdateData"/>
<table width="50%" border="1" class="signup" align="center">
<tr>
<td colspan="2" align="center">
<font size="4" color="#660099">
Please Enter the Following Details</font><br>
</td>
</tr>
<!-<tr>
<td align="right" width="50%"><b>Id</b></td>
<td width="50%" align="left">
<html:text
property="id" size="30" maxlength="120"/>
</td>
</tr>
-->
<tr><td colspan="2"

236
align="center"><font color="red"><html:errors/></font>
</td></tr>
<tr>
<td align="right"
width="50%"><b>User Id<font color="#FF0000">*</font></b></td>
<td align="left" width="50%">
<html:text property="userid" size="30" maxlength="120"/>
</td>
</tr>
<tr>
<td align="right"><b>
Password<font color="#FF0000">*</font></b></td>
<td align="left">
<html:password
property="password" size="30" maxlength="120"/>
</td>
</tr>
<tr>
<td align="right"><b>Email</b></td>
<td align="left">
<html:text property="email" size="30" maxlength="120"/>
</td>
</tr>
<tr>
<td align="right"><b>Address</b></td>
<td align="left">
<html:text property="address" size="30" maxlength="120"/>
</td>
</tr>
<tr>
<td align="right"><b>Phone No.<b></td>
<td align="left">
<html:text property="phno" size="30" maxlength="120"/>
</td>
</tr>
<tr><td colspan="2"> </td></tr>
<tr>
<td align="center" colspan="2">
<html:submit>Save</html:submit>
</td>
</tr>
</table>
</html:form>
<!-</td>
</tr>
</table>
</center>
-->
</body>
</html:html>
Struts Registration Form

237
Registration form of the application which is associated with the ActionMapping "/userregister", which is
action mapping used for registering the user. Here is code of Registration Form:
package web.struts.form;
import javax.servlet.http.HttpServletRequest;
import org.apache.struts.action.*;
public class UserRegisterForm extends ActionForm{
private String action="add";
private String actionUpdateData;
private Integer id;
private String userid;
private String password;
private String email;
private String address;
private String phno;
public void reset(ActionMapping mapping,HttpServletRequest
request){
this.id = null;
this.userid=null;
this.password=null;
this.email=null;
this.address=null;
this.phno=null;
this.action="add";
this.actionUpdateData="";
}
public ActionErrors validate(ActionMapping mapping, HttpServletRequest request ) {
ActionErrors errors = new ActionErrors();
return errors;
}
public String getAction() {
return action;
}
public void setAction(String action) {
this.action = action;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {

238
this.password = password;
}
public String getPhno() {
return phno;
}
public void setPhno(String phno) {
this.phno = phno;
}
public String getUserid() {
return userid;
}
public void setUserid(String userid) {
this.userid = userid;
}
public String getActionUpdateData() {
return actionUpdateData;
}
public void setActionUpdateData(String actionUpdateData) {
this.actionUpdateData = actionUpdateData;
}
public Integer getId() {
return id; }
public void setId(Integer id) {
this.id = id;
}
}
Success JSP Page
Success page confirms the successful completion of user registration. Here is the code of the success jsp
page (registersuccess.jsp):
<%@ taglib uri="/tags/struts-bean" prefix="bean" %>
<%@ taglib uri="/tags/struts-html" prefix="html" %>
<html:html locale="true">
<head>
<title></title>
<html:base/>
</head>
<body>
<%@ include file="../top.jsp"%>
<center>
<p><b>You are register successfuly !</b></p>
</center>
</body>
</html:html>
Above jsp page (registersuccess.jsp) should be saved into project\pages\user directory.
In this section we have developed JSP file and Struts action form for our application.

239
Developing Action Class
The Action Class UserRegisterAction.java process the user registration request. It saves the user
information into database with the help of "SpringHibernateDao" bean.
Here is the full code of UserRegisterAction.java:
package web.struts.action;
import
import
import
import
import

services.ServiceFinder;
web.struts.form.UserRegisterForm;
javax.servlet.http.HttpServletRequest;
javax.servlet.http.HttpServletResponse;
javax.servlet.http.HttpSession;

import
import
import
import
import
import

org.apache.struts.action.Action;
org.apache.struts.action.ActionForm;
org.apache.struts.action.ActionForward;
org.apache.struts.action.ActionMapping;
org.apache.struts.action.ActionMessage;
org.apache.struts.action.ActionMessages;

public class UserRegisterAction extends Action {


public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
UserRegisterForm objForm = (UserRegisterForm) form;
//Utilities util=new Utilities();
// Retrieve the DAO Reference
dao.SpringHibernateDAO springHibernateDAO = (dao.SpringHibernateDAO)
ServiceFinder
.getContext(request).getBean("SpringHibernateDao");
//By Default show the Add/Edit Page
String forwardToPage = "input";
String strError = "";
try {

String strParent = "0";


boolean ValidUsernameStatus = springHibernateDAO
.checkValidUserName(objForm.getUserid());

//In case of form submit Add/Update the data


if (objForm.getActionUpdateData().equals("update")) {
//In case of Add, Add the data into database
if (objForm.getAction().equals("add")) {

240

if (ValidUsernameStatus == false) {
dao.hibernate.Login pojoObj = new dao.hibernate.Login();
pojoObj.setLoginid(objForm.getUserid());
pojoObj.setPassword(objForm.getPassword());
pojoObj.setAddress(objForm.getAddress());
pojoObj.setPhno(Integer.parseInt(objForm.getPhno()));
pojoObj.setId(objForm.getId());
pojoObj.setEmail(objForm.getEmail());
//Add the data
springHibernateDAO.addUser(pojoObj);
forwardToPage = "success";
} else {
// Create object of ActionMesssages
ActionMessages errors = new ActionMessages();
errors.add("invalidUsername", new ActionMessage(
"error.invalidUsername.invalid"));
saveErrors(request, errors);
return mapping.findForward("input");
}
}//User updates the data, update the user details
if (objForm.getAction().equals("update")) {
//System.out.println("Update the Data");
dao.hibernate.Login pojoObj = springHibernateDAO
.loadUser(objForm.getId().toString());
pojoObj.setLoginid(objForm.getUserid());
pojoObj.setPassword(objForm.getPassword());
pojoObj.setAddress(objForm.getAddress());
pojoObj.setPhno(Integer.parseInt(objForm.getPhno()));
pojoObj.setId(objForm.getId());
pojoObj.setEmail(objForm.getEmail());
//Update the data
springHibernateDAO.updateUser(pojoObj);
forwardToPage = "updated";
}
}
//In case of Edit retrieve the data from datbase and set the values in the form obj
if (objForm.getAction().equals("Edit")) {
HttpSession session = request.getSession();
String id = (String)session.getAttribute("ID");

241

//Retrieve the data from database


dao.hibernate.Login pojoObj = springHibernateDAO.loadUser(id);
objForm.setId(pojoObj.getId());
objForm.setUserid(pojoObj.getLoginid());
objForm.setPassword(pojoObj.getPassword());
objForm.setAddress(pojoObj.getAddress());
objForm.setEmail(pojoObj.getEmail());
objForm.setPhno(String.valueOf(pojoObj.getPhno()));
//for the edit form
forwardToPage = "input";
//Set the action to update
objForm.setAction("update");
}
} catch (Exception e) {
forwardToPage = "input";
strError = e.getMessage();
System.out.println("===> Error:" + strError);
}
//Display the registration form to the user
return mapping.findForward(forwardToPage);
}
}
Save the above code into the file UserRegisterAction.java in the project\WEBINF\src\java\\web\struts\action directory.
Understanding the Action Class
a) Getting the SpringHibernateDao Reference
Following code gets the reference of SpringHibernate.
//Retrieve the DAO Reference
dao.SpringHibernateDAO springHibernateDAO = (dao.SpringHibernateDAO) ServiceFinder
.getContext(request).getBean("SpringHibernateDao");
b) Checking for the New user Registration
Following code checks for the user restoration information. This is necessay as we using the same action
class (UserRegistrationAction.java) for modification of user profile.
if (objForm.getAction().equals("add")) {
//The Save the user information into database
}
c) Creation and populating the POJO object
We are using Hibernate so, to persist the User information into database we will first create object of
Login class and populate it with requied data.
dao.hibernate.Login pojoObj = new dao.hibernate.Login();
pojoObj.setLoginid(objForm.getUserid());
pojoObj.setPassword(objForm.getPassword());
pojoObj.setAddress(objForm.getAddress());
pojoObj.setPhno(Integer.parseInt(objForm.getPhno()));

242
pojoObj.setId(objForm.getId());
pojoObj.setEmail(objForm.getEmail());
c) Persisting the POJO object
Following code persists the data into database.
//Update the data
springHibernateDAO.updateUser(pojoObj);
Configurations to be made into struts-config.xml
a) Add the form bean entry:
<form-bean name="UserRegisterForm"
type="web.struts.form.UserRegisterForm">
</form-bean>
b) Action mapping entry:
<action
path="/userregister"
name="UserRegisterForm"
scope="request"
validate="true"
input="/pages/user/userRegister.jsp"
type="web.struts.action.UserRegisterAction">
<forward name="success" path="/pages/user/registersuccess.jsp"/>
<forward name="input" path="/pages/user/userRegister.jsp"/>
<forward name="updated" path="/pages/user/updatesuccess.jsp"/>
</action>
Now the registration form is ready to test. You can compile and run the application to test the
Registration Form.

Login form in struts: Whenever you goes to access data from database, as a register user you are
always asked for the login to accessing data. E-mail's login are very good example of this. In this
section of struts tutorial we will explain how to do coding for a login form using struts.
UserLoginAction Class: When you download Login and User Registration Application from
http://www.net/struts/hibernate-spring/project.zip, you will get a jar file .After extracting this jar file you
will get UserLoginAction.java file in action directory. We use this UserLoginAction.java to process
request and Login user.
package web.struts.action;
import web.struts.form.UserLoginForm;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import
import
import
import
import
import

org.apache.struts.action.Action;
org.apache.struts.action.ActionForm;
org.apache.struts.action.ActionForward;
org.apache.struts.action.ActionMapping;
org.apache.struts.action.ActionMessage;
org.apache.struts.action.ActionMessages;

import services.ServiceFinder;
public class UserLoginAction extends Action{

243
public ActionForward execute(ActionMapping mapping,ActionForm form,HttpServletRequest
request,HttpServletResponse response) throws Exception{
dao.SpringHibernateDAO springHibernateDAO = (dao.SpringHibernateDAO)
ServiceFinder.getContext(request).getBean("SpringHibernateDao");
ActionMessages errors = new ActionMessages();
UserLoginForm objForm = (UserLoginForm) form;
String strUserid=objForm.getUserid();
String strPassword=objForm.getPassword();
boolean loginStatus = springHibernateDAO.checkUserLogin(strUserid,strPassword);
if(loginStatus==true){
HttpSession session = request.getSession();
session.setAttribute("userID", strUserid);
//int id =springHibernateDAO.getUserId(strUserid);
String id=String.valueOf(springHibernateDAO.getUserId(strUserid));
//Integer idvalue=new Integer(id);
session.setAttribute("ID", id);
System.out.println("Session value:"+session.getAttribute("userID"));
return mapping.findForward("success");
} else {
// not allowed
errors.add("login",new ActionMessage("error.login.invalid"));
saveErrors(request,errors);
return mapping.findForward("failure");
}
}
}

Create action extends Action class. execute( ) method of Action class. This method Processes the
specified HTTP request and create the corresponding HTTP response or forward to another web
component.

to retrieve the DAO Reference.


dao.SpringHibernateDAO springHibernateDAO = (dao.SpringHibernateDAO)
ServiceFinder.getContext(request)
.getBean("SpringHibernateDao");

244

create ActionMessages object to save errors and call them in jsp page.
// Create object of ActionMesssages
ActionMessages errors = new ActionMessages();
Now we create a action form object to access the value enter by user.
UserLoginForm objForm = (UserLoginForm) form;

checkUserLogin(strUserid,strPassword) .will return the status of valid user.


If user name and password is valid status will be true otherwise false. This method body is in
SpringHibernateDAO class.
boolean loginStatus = springHibernateDAO.checkUserLogin(strUserid,strPassword);

this code is from dao.SpringHibernateDAOImpl.java


public boolean checkUserLogin(String strUserName, String strPassword) throws
DataAccessException,java.sql.SQLException{
boolean valid = false;
Connection conn = this.getSession().connection();

//Write jdbc code to validate the user against database


Statement smt = conn.createStatement();
ResultSet rs;

//select query for checking password


String query="select id from login where loginid='"+strUserName+"' and password='"+strPassword+"'";
rs=smt.executeQuery(query);
if(rs.next()== true){
valid=true;
}else{
valid=false;
}
smt.close();
rs.close();
conn.close();
return valid;
}
If the loginStatus is true then set the value of username and id in session and
mapping.findForward("success") return success jsp page. Otherwise add this error in ActionMessages
object.

245
errors.add("login",new ActionMessage("error.login.invalid"));
saveErrors(request,errors);

and mapping.findForward("failure") return failure. Now jsp page return with errors.
ActionForm:An ActionForm is a JavaBean that extends org.apache.struts.action.ActionForm.in this
application ActionForm is UserLoginForm.java.ActionForm maintains the session state for web application
and the ActionForm object is automatically populated on the server side with data entered from a form
on the client side. It must have setters and getters for all the form fields.It must have setters and
getters for all the form fields.
package web.struts.form;
import javax.servlet.http.HttpServletRequest;
import org.apache.struts.action.*;
public class UserLoginForm extends ActionForm{
private String action="add";
private String userid = null;
private String password = null;
public void reset(ActionMapping mapping,HttpServletRequest request){
this.userid=null;
this.password=null;
this.action="add";
}
public ActionErrors validate(
ActionMapping mapping, HttpServletRequest request ) {
ActionErrors errors = new ActionErrors();
/*
if( getUserid() == null || getUserid().length() < 1 ) {
errors.add("username",new ActionMessage("error.username.required"));
}
if( getPassword() == null || getPassword().length() < 1 ) {
errors.add("password",new ActionMessage("error.password.required"));
}
*/
return errors;
}

246
public String getAction() {
return action;
}
public void setAction(String action) {
this.action = action;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getUserid() {
return userid;
}
public void setUserid(String userid) {
this.userid = userid;
}
}

Action mapping in struts-config.xml: Action mapping associates a Struts action with a forward
which is responsible for request processing. The following is mapping for Action Form .
<form-bean name="UserLoginForm"
type="web.struts.form.UserLoginForm">
</form-bean>
This is mapping for action class<action
path="/userlogin"
name="UserLoginForm"
scope="request"
validate="true"
input="/pages/user/userlogin.jsp"
type="web.struts.action.UserLoginAction">
<forward name="success" path="/pages/user/loginsuccess.jsp"/>
<forward name="failure" path="/pages/user/userlogin.jsp"/>
</action>

View Part(jsp file): The View portion of this application is constructed using JavaServer Pages (JSP)

247
technology.This JSP shows Login form user interface.
This line of code is responsible for errors generated by Action Class or Action Form.
Action Form returns ActionErrors and Action Class returns errors saved in the form of ActionMessage.
<html:errors/>
<%@ taglib uri="/tags/struts-bean" prefix="bean" %>
<%@ taglib uri="/tags/struts-html" prefix="html" %>
<html:html locale="true">
<head>
<title><bean:message key="welcome.title"/></title>
<LINK rel="stylesheet" type="text/css" name="anyname" href="<html:rewrite
page='/css/style.css'/>">
</head>
<html:base/>
<body>
<%@ include file="../top.jsp"%>
<center>
<table width="40%">
<tr>
<!-<td colspan="5">
<table width="400" border="1" cellpadding="0" cellspacing="0" align="center" >
<tr>
-->

<td>
<html:form action="/userlogin" method="post">
<table border="1" cellspacing="2" cellpadding="1" width="100%" class="signup">
<tr>
<td align="center" colspan="2" ><font size="5">User Login</font><br><font
color="red"><html:errors/></td>
</tr>
<tr align="center">
<td align="right" width="50%"><b>User ID:</b></td>
<td width="50%"><html:text property="userid" size="30" maxlength="30"/></td>
</tr>
<tr align="center">
<td align="right"><b>Password:</b></td>
<td><html:password property="password" size="30" maxlength="30"/></td>
</tr>
<tr>
<td align="center" colspan="2"><html:submit>Sign-In !</html:submit></td>
</tr>

248

</table>
</html:form>
</td>
<!-</tr>
</table>
</td> -->
</tr>
</table>
</center>
<body>
</html:html>
Developing Login Action Class

In any application the login process is one of the most important task done by the developer. The login
action class is responsible for performing success full login. It get the user id and password from the
login form and checks the login id and their corresponding password in the database. If matching is
found the login action forwarded the action to the home page otherwise it retain the data at the login
page with some error.
Following are the necessary steps followed in login process.
Get the login information from the user

Developing Login Action Class


In any application the login process is one of the most important task done by the developer. The login
action class is responsible for performing success full login. It get the user id and password from the
login form and checks the login id and their corresponding password in the database. If matching is
found the login action forwarded the action to the home page otherwise it retain the data at the login
page with some error.

Following are the necessary steps followed in login process.


Get the login information from the user
UserLoginForm objForm = (UserLoginForm) form;
String strUserid = objForm.getUserid();

249
String strPassword = objForm.getPassword();

Check the user id and password in the database


boolean loginStatus = springHibernateDAO.checkUserLogin(strUserid,
strPassword);

If User id and there corresponding password is matches then add the user Id on the session and check
on every pages where security is neccessary
HttpSession session = request.getSession();
session.setAttribute("userID", strUserid);
String id = String.valueOf(springHibernateDAO.getUserId(strUserid));
session.setAttribute("ID", id);

And finally return the success


return mapping.findForward("success");

Following are the views which shows the login process Login form
Returns when User Id or password is incorrect

On correct user id and password the action is forwarded to the home page

Developing Forgot Password Form


The forgot password form will be used, when user forgot their password. This form will get the user
name and password from the user and forwarded it to the forgot password action, the forgot password
action is responsible for forwarding user login name and password to the user. This form will take the
user name and password and forgot password action action will compare the form value with the
registered value from the database. The form should be developed in such a manner that it can take
valid data from the user, therefore form validation must be implemented correctly.

250
As you know struts framework have there own set of tag libraries for developing a JSP file. Therefore will
user the struts specific tag libraries

Please consider the steps for developing forgot password form


At first import the tag libraries which will be used during writing a JSP page as,
<%@ taglib uri="/tags/struts-bean" prefix="bean" %>
<%@ taglib uri="/tags/struts-html" prefix="html" %>

Set the page title and import the CSS style sheet in your page
<head>
<title><bean:message key="welcome.title"/></title>
<LINK rel="stylesheet" type="text/css" name="anyname" href="<html:rewrite
page='/css/style.css'/>">
</head>

Make a form using Struts tag


<html:form action="/userforgetpassword" method="post">
</html:form>

Make two text fields for, one for user name and other for email address, remember that the properties
values must be same as you have typed in its bean class
<td align="right">User Name:</td>
<td align="left"><html:text property="username" size="30" maxlength="30"/></td>
<td align="right">Email:</td>
<td><html:text property="email" size="30" maxlength="30"/></td>
<td align="center" colspan="2"><html:submit>Send Me My Username and
Password</html:submit></td>

The form validation will be done in the bean class (server side) in the validate method and if any invalid
field is found the bean will return an action error

The complete code of fogot passowrd JSP is given below


forgotPassword.jsp

251
<%@ taglib uri="/tags/struts-bean" prefix="bean"%>
<%@ taglib uri="/tags/struts-html" prefix="html"%>
<html:html locale="true">
<head>
<title><bean:message key="welcome.title" /></title>
<LINK rel="stylesheet" type="text/css" name="anyname"
href="<html:rewrite page='/css/style.css'/>">
</head>
<html:base />
<body>
<%@ include file="../top.jsp"%>
<center>
<table width="40%">
<tr>
<td><html:form action="/userforgetpassword" method="post">
<table border="0" cellspacing="2" cellpadding="1" width="100%"
class="signup">
<tr>
<td align="center" colspan="2"><font size="5">Access
Your Username and password</font></td>
</tr>
<tr>
<td align="center" colspan="2"><font color="red"><html:errors /></font></td>
</tr>
<tr>
<td colspan="2">
<p>&nbsp</p>
</td>
</tr>
<tr>
<td colspan="2">
<li>Enter your user name as registered</li>
</td>
</tr>
<tr align="center">
<td align="right">User Name:</td>
<td align="left"><html:text property="username" size="30"
maxlength="30" /></td>
</tr>
<tr>
<td colspan="2">
<p> </p>
</td>
</tr>
<tr>
<td colspan="2">
<li>OR If you do not remember your username, then enter your
e-mail address as entered in your resume:</li>
</td>
</tr>
<tr>
<td align="right">Email:</td>

252
<td><html:text property="email" size="30" maxlength="30" /></td>
</tr>
<tr>
<td colspan="2">
<p> </p>
</td>
</tr>
<tr>
<td align="center" colspan="2"><html:submit>Send Me My Username and
Password</html:submit></td>
</tr>
<!-- <tr><td colspan="2"><p> </p></td></tr> -->
</table>
</html:form></td>
</tr>
</table>
</center>
</body>
</html:html>

Forgot Password Action


The password forgot Action is invoked when you forgot your password and want to recover the
password. The forgot password action requires user name and passwords same as you had entered
during registration. This given values are matched from the database in the forgot password action, if
the value matches the action sends an email of user name and passwords to the user email account.
The development process of ForgotPasswordAction is as follows.
At first get the entered data (User Name & Email Address) from the forgot password form
UserForgetPasswordForm forgetform = (UserForgetPasswordForm) form;
String strUserName=forgetform.getUsername();
String strEmail=forgetform.getEmail();

Then retrive a DAO(Data Access Object Reference) and get the user deatail from the database and
compare it
dao.SpringHibernateDAO springHibernateDAO = (dao.SpringHibernateDAO)
ServiceFinder.getContext(request)
.getBean("SpringHibernateDao");
String[] strPasswordEmail =
springHibernateDAO.retriveUserForgetPassword(strUserName,strEmail);

If comparison is correct then add the user detail and send an email.....
String [] reciepent={strPasswordEmail[1]};
String username=strPasswordEmail[2];

253
String subject="Your username & password ";
String message="Hi,"+username;
message+="\n Your username is "+username+".";
message+="\n Your password is "+strPasswordEmail[0]+".";
message+="\n Please login to the web site with your username and password.";
message+="\n \n Thanks";
message+="\n \n \n Regards";
String from=web.common.ProjectConstants.FROM_MAIL;
mailBean.sendMail(reciepent,subject,message,from);

The complete code of forgot password action is given below

UserForgetPasswordAction.java
package web.struts.action;
import web.struts.form.UserForgetPasswordForm;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import
import
import
import
import
import

org.apache.struts.action.Action;
org.apache.struts.action.ActionForm;
org.apache.struts.action.ActionForward;
org.apache.struts.action.ActionMapping;
org.apache.struts.action.ActionMessages;
org.apache.struts.action.ActionMessage;

import services.ServiceFinder;
public class UserForgetPasswordAction extends Action
{
public ActionForward execute(
ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response) throws Exception{
//Retrieve the DAO Reference
dao.SpringHibernateDAO springHibernateDAO = (dao.SpringHibernateDAO)
ServiceFinder.getContext(request)
.getBean("SpringHibernateDao");
//

Retrieve the Mail Bean Reference


web.common.SendMail mailBean = (web.common.SendMail)
ServiceFinder.getContext(request).getBean(web.common.ProjectConstants.MAIL_BEAN);

254
// Create object of ActionMesssages
ActionMessages errors = new ActionMessages();
UserForgetPasswordForm forgetform = (UserForgetPasswordForm) form;
String strUserName=forgetform.getUsername();
String strEmail=forgetform.getEmail();
String[] strPasswordEmail =
springHibernateDAO.retriveUserForgetPassword(strUserName,strEmail);
if(strPasswordEmail[0] != null && strPasswordEmail[1] != null){
System.out.println("Password:"+strPasswordEmail[0]);
System.out.println("email:"+strPasswordEmail[1]);
//sending mail
String [] reciepent={strPasswordEmail[1]};
String username=strPasswordEmail[2];
String subject="Your username & password ";
String message="Hi,"+username;
message+="\n Your username is "+username+".";
message+="\n Your password is "+strPasswordEmail[0]+".";
message+="\n Please login to the web site with your username and password.";
message+="\n \n Thanks";
message+="\n \n \n Regards";
// getting from emailid from allcooljobs.web.common.CollJobsConstants
String from=web.common.ProjectConstants.FROM_MAIL;
try{
mailBean.sendMail(reciepent,subject,message,from);
}catch(Exception e){
System.out.println("Error in sending mail:"+e);
}
return mapping.findForward("success");
}else{
errors.add("invalid",new ActionMessage("error.usernameEmail.invalid"));
saveErrors(request,errors);
}
}

return mapping.findForward("failure");

255
This facility is used for updating user information in the database. Such as login id, name, password,
email address etc. When user wishes to change their information, he may proceed by clicking on Update
Profile Menu, all the information is fetched from the database and set in the update form. then used can
change their personal information.
In this section at first we see how the update form is developed after this we will discuss how to develop
an action.

Developing an update form

At first import the struts specific tag libraries


<%@ taglib uri="/tags/struts-bean" prefix="bean"%>
<%@ taglib uri="/tags/struts-html" prefix="html"%>

Then make a form


<html:form action="/userregister" method="post" onsubmit="return validateForm(this);">
User Id <html:text property="userid" size="30" maxlength="120" />
Password <html:password property="password" size="30" maxlength="120" />
Email <html:text property="email" size="30" maxlength="120" />
Address <html:text property="address" size="30" maxlength="120" />
Phone No <html:text property="phno" size="30" maxlength="120" />
<html:submit>Save</html:submit>
</html:form>

Update Action
The Update action is responsible for setting value in the bean properties
It get the user id from the session and fetch all the information from the database of that user and sets
into the bean properties file
HttpSession session = request.getSession();

256
String id = (String) session.getAttribute("ID");
dao.hibernate.Login pojoObj = springHibernateDAO
.loadUser(id);

objForm.setId(pojoObj.getId());
objForm.setUserid(pojoObj.getLoginid());
objForm.setPassword(pojoObj.getPassword());
objForm.setAddress(pojoObj.getAddress());
objForm.setEmail(pojoObj.getEmail());
objForm.setPhno(String.valueOf(pojoObj.getPhno()));
forwardToPage = "input";

When user submits the form it saves all the values to the database as
dao.hibernate.Login pojoObj = springHibernateDAO
.loadUser(objForm.getId().toString());
pojoObj.setLoginid(objForm.getUserid());
pojoObj.setPassword(objForm.getPassword());
pojoObj.setAddress(objForm.getAddress());
pojoObj.setPhno(Integer.parseInt(objForm.getPhno()));
pojoObj.setId(objForm.getId());
pojoObj.setEmail(objForm.getEmail());
springHibernateDAO.updateUser(pojoObj);
forwardToPage = "updated";

Struts 2 DIRECT REDIRECT


<result name="redirect" type="redirect">${url}</result>

257
Configure and use spring webflow from Spring MVC
allrequeststoaflowfirstgothroughSpringMVCsDispatcherServlet.Fromthere,ahandfulofspecial
beans in the Spring application context must be configured to han- dle the flow request and execute the
flow.
SeveralofthewebflowbeansaredeclaredusingelementsfromSpringWebFlowsSpringconfiguration
XMLnamespace.Therefore,wellneedtoaddthenamespacedeclarationtothecontextdefinition XML
file: <?xml version="1.0"encoding="UTF-8"?>
<beans.>
flow executor drives the execution of a flow, flow:flow-executor> element creates a flow executor in
Spring
<flow:flow-executor id="flowExecutor" flow-registry="flowRegistry" />
<flow:flow-registry> element like this:
<flow:flow-registryid="flowRegistry" base-path="/WEB-INF/flows">
<flow:flow-location-patternvalue="*-flow.xml"/> </flow:flow-registry>
any XML file whose name ends with -flow.xml will be considered a flow definition.
the FlowHandlerMappingiswiredwithareferencetotheflowregistrysoitknowswhenarequestsURL
maps to a flow
<bean class="org.springframework.webflow.mvc.servlet.FlowHandlerAdapter">
<property name="flowExecutor" ref="flowExecutor" /> </bean>
This handler adapter is the bridge between DispatcherServlet and Spring Web Flow. It handles flow
requests and manipulates the flow based on those requests.

Potrebbero piacerti anche