Sunteți pe pagina 1din 87

Core Java

Q) What is difference between Java and C++?


A) (i) Java does not support pointers. Pointers are inherently insecure and troublesome. Since pointers do not exist in
Java. (ii) Java does not support operator overloading. (iii) Java does not perform any automatic type conversions that
result in a loss of precision (iv) All the code in a Java program is encapsulated within one or more classes. Therefore
Java does not have global variables or global functions. (v) Java does not support multiple inheritances.
Java does not support destructors but rather add the finali!e () function. (vi)Java does not have the delete operator.
(vii) The "" and ## are not overloaded for $%& operations
Q) Opps concepts
Polymorphism
Ability to ta'e more than one form in (ava we achieve this using )ethod &verloading (compile time polymorphism)
)ethod overriding (runtime polymorphism)
Inheritance
$s the process by which one ob(ect ac*uires the properties of another ob(ect+ The advantages of inheritance are
reusability of code and accessibility of variables and methods of the super class by subclasses.
Encapslation
,rapping of data and function into a single unit called encapsulation. -x. / all (ava programs.
!Or)
0othing but data hiding li'e the variables declared under private of a particular class are accessed only in that class
and cannot access in any other the class. &r 1iding the information from others is called as -ncapsulation. &r
-ncapsulation is the mechanism that binds together code and data it manipulates and 'eeps both safe from outside
interference and misuse.
"bstraction
0othing but representing the essential features without including bac'ground details.
#ynamicbindin$
2ode associated with a given procedural call is not 'nown until the time of the call at runtime. 3ynamic binding
is nothing but late binding.
Q) class % ob&ect?
class class is a blue print of an ob(ect
Ob&ect instance of class.
Q) Ob&ect creation?
&b(ect is constructed either on a memory heap or on a stac'.
'emory heap
4enerally the ob(ects are created using the new 'eyword. Some heap memory is allocated to this newly created
ob(ect. This memory remains allocated throughout the life cycle of the ob(ect. ,hen the ob(ect is no more referred
the memory allocated to the ob(ect is eligible to be bac' on the heap.
(tac)
3uring method calls ob(ects are created for method arguments and method variables. These ob(ects are created on
stac'.
Q) (ystem*ot*println!)
println() is a methd of (ava.io.print,riter.
5out6 is an instance variable of (ava.lang.System class.
Q) +ransient % volatile
Transient //# The transient modifier applies to variables only the ob(ect are variable will not persist. Transient
variables are not seriali!ed.
7olatile //# value will be changed unexpectedly by the other part of the program "it tells the compiler a variable
may change asynchronously due to threads"

Q) "ccess (pecifiers % "ccess modifiers?
Access Specifiers A.S gives access privileges to outside of application !or) others, they are Public Protected
Private 3efaults.
Access )odifiers A.) which gives additional meaning to data methods and classes final cannot be modified at any
point of time.
Private Pblic Protected -o modifier
(ame class 0o 8es 8es 8es
(ame pac)a$e (bclass 0o 8es 8es 8es
(ame pac)a$e non.sbclass 0o 8es 8es 8es
#ifferent pac)a$e sbclass 0o 8es 8es 0o
#ifferent pac)a$e non.sbclass 0o 8es 0o 0o
Q) #efalt /ales
long /9:;< to 9:;< => ?@ double ?.?d
$nt /9:<> to 9:<> => ? Aloat ?.?f
Short /9:>B to 9:>B => ? Coolean Aalse
Cyte /9:D to 9:D => ? 2har ? to 9:D => null character (or) EFu ????G

Q) 0yte code % JI+ compiler % J/' % J1E % J#2
Cyte code is a highly optimi!ed set of instructions. J7) is an interpreter for byte code. Translating a (ava program
into byte code helps ma'es it much easier to run a program in a wide variety of environment.
J7) is an interpreter for byte code
J$T (Just $n Time) is a part of J7) it compiles byte code into executable code in real time will increase the
performance of the interpretations.
JH- is an implementation of the Java 7irtual )achine which actually executes Java programs.
J3I is bundle of software that you can use to develop Java based software Tools provided by J3I is
(i) (avac = compiler (ii) (ava = interpretor (iii) (db = debugger (iv) (avap / 3isassembles
(v) appletviewer = Applets (vi) (avadoc / documentation generator (vii) (avah / J2J header file generator
Q) Wrapper classes
Primitive data types can be converted into ob(ects by using wrapper classes. These are (ava.lang.pac'age.
Q) #oes Java pass method ar$ments by vale or by reference?
Java passes all arguments by value not by reference
Q) "r$ments % Parameters
,hile defining method variable passed in the method are called parameters. ,hile using those methods values
passed to those variables are called arguments.
Q) Pblic static void main !(trin$ 34 ar$s)
,e can over@oad the main() method.
,hat if the main method is declared as 5Private6+
The program compiles properly but at runtime it will give K)ain method not public.K )essage
,hat if the static modifier is removed from the signature of the main method+
Program compiles. Cut at runtime throws an error K0oSuch)ethod-rrorK.
,e can write 5static pblic void6 instead of 5pblic static void6 but not 5pblic void static6.
Protected static void main!)5 static void main!)5 private static void main!) are also valid.
$f $ do not provide the String array as the argument to the method+
Program compiles but throws a runtime error K0oSuch)ethod-rrorK.
If no ar$ments on the command line5 (trin$ array of 'ain method will be empty or nll?
$t is empty. Cut not null.
7ariables can have the same name as a method or a class
Q) Can an application have mltiple classes havin$ main!) method?
A) 8es it is possible. ,hile starting the application we mention the class name to be run. The J7) will loo' for the )ain
method only in the class whose name you have mentioned. 1ence there is not conflict amongst the multiple classes
having main method.
Q) Can I have mltiple main methods in the same class?
A) 0o the program fails to compile. The compiler says that the main method is already defined in the class.
Q) Constrctor
The automatic initiali!ation is performed through the constructor constructor has same name has class name.
2onstructor has no return type not even void. ,e can pass the parameters to the constructor. this() is used to invo'e a
constructor of the same class. Super() is used to invo'e a super class constructor. 2onstructor is called immediately
after the ob(ect is created before the new operator completes.
2onstructor can se the access modifiers pblic5 protected5 private or have no access modifier
2onstructor can not use the modifiers abstract5 static5 final5 native5 synchroni6ed or strictfp
2onstructor can be overloaded we cannot override.
8ou cannot use this!) and (per!) in the same constructor.
2lass AL
A()L
System.out.println(5hello6)M
NN
2lass C extends A L
C()L
System.out.println(5friend6)M
NN
2lass print L
Public static void main (String args OP)L
C b Q new C()M
N
o%p./ hello friend
Q) #iff Constrctor % 'ethod
Constrctor 'ethod
7se to instance of a class 8ropin$ &ava statement
-o retrn type /oid !or) valid retrn type
(ame name as class name "s a name e9cept the class method name5 be$in
with lower case*
:+his; refer to another constrctor in the same
class
1efers to instance of class
:(per; to invo)e the sper class constrctor E9ecte an overridden method in the sper class
:Inheritance; cannot be inherited Can be inherited
We can :overload; bt we cannot :overridden; Can be inherited
Will atomatically invo)e when an ob&ect is
created
'ethod has called e9plicitly
Q) 8arba$e collection
4.2 is also called automatic memory management as J7) automatically removes the unused variables%ob(ects
(value is null) from the memory. Rser program cannJt directly free the ob(ect from memory instead it is the (ob of the
garbage collector to automatically free the ob(ects that are no longer referenced by a program. -very class inherits
finali6e!) method from &ava*lan$*Ob&ect the finali!e() method is called by garbage collector when it determines no
more references to the ob(ect exists. $n Java it is good idea to explicitly assign nll into a variable when no more in use
calling (ystem*$c!) and 1ntime*$c!)5 J7) tries to recycle the unused ob(ects but there is no guarantee when all the
ob(ects will garbage collected. 4arbage collection is a low/priority thread.
4.2 is a low priority thread in (ava 4.2 cannot be forced explicitly. J7) may do garbage collection if it is running short
of memory. The call System.gc() does 0&T force the garbage collection but only suggests that the J7) may ma'e an
effort to do garbage collection.
Q) <ow an ob&ect becomes eli$ible for 8arba$e Collection?
A) An ob(ect is eligible for garbage collection when no ob(ect refers to it An ob(ect also becomes eligible when its
reference is set to null. The ob(ects referred by method variables or local variables are eligible for garbage collection
when they go out of scope.
$nteger i Q new $nteger(D)M
i Q nullM
Q) =inal5 =inally5 =inali6e
=inal> . ,hen we declare a sub class a final the compiler will give error as 5cannot subclass final class6 Ainal to prevent
inheritance and method overriding. &nce to declare a variable as final it cannot occupy memory per instance basis.
Ainal class cannot have static methods
Ainal class cannot have abstract methods (Cecause of final class never allows any class to inherit it)
Ainal class can have a final method.
=inally> . Ainally create a bloc' of code that will be executed after try catch bloc' has completed. Ainally bloc' will
execute whether or not an exception is thrown. $f an exception is thrown the finally bloc' will execute even if no catch
statement match the exception. Any time a method is about to return to the caller from inside try%catch bloc' via an
uncaught exception or an explicit return statement the finally clause is also execute.
Rsing System.exit() in try bloc' will not allow finally code to execute
=inali6e> . some times an ob(ect need to perform some actions when it is going to destroy if an ob(ect holding some
non/(ava resource such as file handle (or) window character font these resources are freed before the ob(ect is going to
destroy.
Q) Can we declare abstract method in final class?
A) $t indicates an error to declare abstract method in final class. Cecause of final class never allows any class to inherit
it.
Q) Can we declare final method in abstract class?
A) $f a method is defined as final then we canGt provide the reimplementation for that final method in itGs derived classes
i.e overriding is not possible for that method. ,e can declare final method in abstract class suppose of it is abstract too
then there is no used to declare li'e that.
Q) (perclass % (bclass
A super class is a class that is inherited whereas subclass is a class that does the inheriting
Q) <ow will implement ?) polymorphism @) mltiple inheritance A) mltilevel inheritance in &ava?
") Polymorphism = overloading and overriding
)ultiple inheritances = interfaces.
)ultilevel inheritance = extending class.
Q) Overloadin$ % Overridin$?
Overloadin$ !Compile time polymorphism)
3efine two or more methods within the same class (or) subclass that share the same name and their nmber
of parameter order of parameter % retrn type are different then the methods are said to be overloaded.
&verloaded methods do not have any restrictions on what retrn type of 'ethod !Heturn type are different) (or)
e9ceptions can be thrown. That is something to worry about with overriding.
&verloading is used while implementing several methods that implement similar behavior but for different data
types.
Overridin$ !1ntime polymorphism)
,hen a method in a subclass has the same name5 retrn type % parameters as the method in the super
class then the method in the subclass is override the method in the super class.
The access modifier for the overriding method may not be more restrictive than the access modifier of the
superclass method.
$f the superclass method is pblic the overriding method must be pblic.
$f the superclass method is protected the overriding method may be protected or pblic.
$f the superclass method is pac)a$e the overriding method may be pac)a$a$e protected or pblic.
$f the superclass methods is private it is not inherited and overriding is not an issue.
)ethods declared as final cannot be overridden.
The throws clause of the overriding method may only include exceptions that can be thrown by the superclass
method including its subclasses.

Only member method can be overriden5 not member variable
class ParentL
int i Q ?M
void amethod()L
System.out.println(Kin ParentK)M
N
N
class 2hild extends ParentL
int i Q >?M
void amethod()L
System.out.println(Kin 2hildK)M
N
N
class TestL
public static void main(StringOP args)L
Parent p Q new 2hild()M
2hild c Q new 2hild()M
System.out.print(KiQKSp.iSK K)M
p.amethod ()M
System.out.print(KiQKSc.iSK K)M
c.amethod()M
N
N
o%p> . iQ? in 2hild iQ>? in 2hild
Q) =inal variable
&nce to declare a variable as final it cannot occupy memory per instance basis.
Q) (tatic bloc)
Static bloc' which exactly executed exactly once when the class is first loaded into J7). Cefore going to the
main method the static bloc' will execute.
Q) (tatic variable % (tatic method
Static variables T methods are instantiated only once per class. $n other words they are class variables not
instance variables. $f you change the value of a static variable in a particular ob(ect the value of that variable changes
for all instances of that class.
Static methods can be referenced with the name of the class. $t may not access the instance variables of that
class only its static variables. Aurther it may not invo'e instance (non/static) methods of that class unless it provides
them with some ob(ect.
,hen a member is declared a static it can be accessed before any ob(ect of its class are created.
$nstance variables declared as static are essentially global variables.
$f you do not specify an initial value to an instance T Static variable a default value will be assigned automatically.
)ethods declared as static have some restrictions they can access only static data they can only call other
static data they cannot refer this or sper.
Static methods cant be overriden to non/static methods.
Static methods is called by the static methods only an ordinary method can call the static methods but static
methods cannot call ordinary methods.
Static methods are implicitly KfinalK because overriding is only done based on the type of the ob(ects
They cannot refer 5this6 are 5super6 in any way.
Q) Class variable % Instance variable % Instance methods % class methods
Instance variable variables defined inside a class are called instance variables with multiple instance of classM each
instance has a variable stored in separate memory location.
Class variables you want a variable to be common to all classes then we crate class variables. To create a class
variable put the 5static6 'eyword before the variable name.
Class methods we create class methods to allow us to call a method without creating instance of the class. To
declare a class method use the 5static6 'ey word .
Instance methods we define a method in a class in order to use that methods we need to first create ob(ects of the
class.
Q) (tatic methods cannot access instance variables why?
Static methods can be invo'ed before the ob(ect is createdM $nstance variables are created only when the new
ob(ect is created. Since there is no possibility to the static method to access the instance variables. $nstance variables
are called called as non/static variables.
Q) (trin$ % (trin$0ffer
String is a fixed length of se*uence of characters String is immutable.
StringCuffer represent growable and writeable character se*uence StringCuffer is mutable which means that its
value can be changed. $t allocates room for >;/addition character space when no specific length is specified.
Java.lang.StringCuffer is also a final class hence it cannot be sub classed. StringCuffer cannot be overridden the
e*uals() method.
Q) Conversions
String to Int Conversion> .
int $ Q integer.value&f(59U6).int7alue()M
int x Q integer.parse$nt(5U<<6)M
float f Q float.value&f(9<.V).float7alue()M
Int to (trin$ Conversion >.
String arg Q String.value&f(>?)M
Q) (per!)
Super() always calling the constructor of immediate super class super() must always be the first statements
executed inside a subclass constructor.
Q) What are different types of inner classes?
A) Nested top-level classes/ $f you declare a class within a class and specify the static modifier the compiler treats the
class (ust li'e any other top/level class. Any class outside the declaring class accesses the nested class with the
declaring class name acting similarly to a pac'age. e.g.outer.inner. Top/level inner classes implicitly have access only
to static variables. There can also be inner interfaces. All of these are of the nested top/level variety.
Member classes / )ember inner classes are (ust li'e other member methods and member variables and access to the
member class is restricted (ust li'e methods and variables. This means a public member class acts similarly to a nested
top/level class. The primary difference between member classes and nested top/level classes is that member classes
have access to the specific instance of the enclosing class.
Local classes / @ocal classes are li'e local variables specific to a bloc' of code. Their visibility is only within the bloc'
of their declaration. $n order for the class to be useful beyond the declaration bloc' it would need to implement a more
publicly available interface. Cecause local classes are not members the modifiers public protected private and static
are not usable.
Anonymous classes / Anonymous inner classes extend local inner classes one level further. As anonymous classes
have no name you cannot provide a constructor.
$nner class inside method cannot have static members or bloc's
Q) Which circmstances yo se "bstract Class % Interface?
//# $f you need to change your design ma'e it an interface.
//# Abstract class provide some default behaviour A.2 are excellent candidates inside of application framewor'. A.2
allow single inheritance model which should be very faster.
Q) "bstract Class
Any class that contain one are more abstract methods must also be declared as an abstract there can be no
ob(ect of an abstract class we cannot directly instantiate the abstract classes. A.2 can contain concrete methods.
Any sub class of an Abstract class must either implement all the abstract methods in the super class or be declared
itself as Abstract.
2ompile time error occur if an attempt to create an instance of an Abstract class.
8ou cannot declare 5abstract constructor6 and 5abstract static method6.
An 5abstract method6 also declared private5 native5 final5 synchroni6ed5 strictfp5 protected*
Abstract class can have static5 final method (but there is no use).
Abstract class have visibility pblic5 private5 protected.
Cy default the methods T variables will ta'e the access modifiers is BdefaltC which is accessibility as pac'age.
An abstract method declared in a non/abstract class.
An abstract class can have instance methods that implement a default behavior.
A class can be declared abstract even if it does not actually have any abstract methods. 3eclaring such a class
abstract indicates that the implementation is somehow incomplete and is meant to serve as a super class for one or
more subclasses that will complete the implementation.
A class with an abstract method. Again note that the class itself is declared abstract otherwise a compile time error
would have occurred.
Abstract class AL
Public abstract callme()M
7oid callmetoo()L
N
N
class C extends A(
void callme()L
N
N
class Abstract3emoL
public static void main(string argsOP)L
C b Q new C()M
b.callme()M
b.callmetoo()M
N
N
Q) When we se "bstract class?
") @et us ta'e the behaviour of animals animals are capable of doing different things li'e flying digging
,al'ing. Cut these are some common operations performed by all animals but in a different way as well. ,hen an
operation is performed in a different way it is a good candidate for an abstract method.
Public Abstarctclass AnimalL
Public void eat(food food) L
N
public void sleep(int hours) L
N
public abstract void ma'e0oise()
N
public 3og extends Animal
L
public void ma'e0oise() L
System.out.println(5Car'W Car'6)M
N
N
public 2ow extends Animal
L
public void ma'e0oise() L
System.out.println(5mooW moo6)M
N
N
Q) Interface
$nterface is similar to class but they lac' instance variable their methods are declared with out any body.
$nterfaces are designed to support dynamic method resolution at run time. All methods in interface are implicitly
abstract even if the abstract modifier is omitted. $nterface methods have no implementationM
Interfaces are sefl for?
a) 3eclaring methods that one or more classes are expected to implement
b) 2apturing similarities between unrelated classes without forcing a class relationship.
c) 3etermining an ob(ectJs programming interface without revealing the actual body of the class.
Why Interfaces?
5&ne interfaces multiple methods 5signifies the polymorphism concept.
$nterface has visibility pblic*
$nterface can be extended T implemented.
An interface body may contain constant declarations abstract method declarations inner classes and inner
interfaces.
All methods of an interface are implicitly "bstract Pblic even if the public modifier is omitted.
An interface methods cannot be declared protected5 private5 strictfp5 native or synchroni6ed.
All /ariables are implicitly final5 pblic5 static fields*
A compile time error occurs if an interface has a simple name the same as any of itJs enclosing classes or interfaces.
An $nterface can only declare constants and instance methods but cannot implement default behavior.
top.level interfaces may only be declared pblic5 inner interfaces may be declared private and protected but only if
they are defined in a class.
A class can only extend one other class.
A class may implements more than one interface.
$nterface can extend more than one interface.
$nterface A
L
final static float pi Q <.>UfM
N
class C implements A
L
public float compute(float x float y) L
return(xXy)M
N
N
class testL
public static void main(String argsOP)
L
A a Q new C()M
a.compute()M
N
N
Q) #iff Interface % "bstract Class?
A.2 may have some executable methods and methods left unimplemented. $nterface contains no implementation
code.
An A.2 can have nonabstract methods. All methods of an $nterface are abstract.
An A.2 can have instance variables. An $nterface cannot.
An A.2 must have subclasses whereas interface canJt have subclasses
An A.2 can define constructor. An $nterface cannot.
An A.2 can have any visibility. public private protected. An $nterface visibility must be public (or) none.
An A.2 can have instance methods that implement a default behavior. An $nterface can only declare constants and
instance methods but cannot implement default behavior.
Q) What is the difference between Interface and class?
A class has instance variable and an $nterface has no instance variables.
&b(ects can be created for classes where as ob(ects cannot be created for interfaces.
All methods defined inside class are concrete. )ethods declared inside interface are without any body.
Q) What is the difference between "bstract class and Class?
2lasses are fully defined. Abstract classes are not fully defined (incomplete class)
&b(ects can be created for classes there can be no ob(ects of an abstract class.
Q) What are some alternatives to inheritance?
") 3elegation is an alternative to inheritance. 3elegation means that you include an instance of another class as an
instance variable and forward messages to the instance. $t is often safer than inheritance because it forces you to thin'
about each message you forward because the instance is of a 'nown class rather than a new class and because it
doesnGt force you to accept all the methods of the super class. you can provide only the methods that really ma'e
sense. &n the other hand it ma'es you write more code and it is harder to re/use (because it is not a subclass).
Q) (eriali6able % E9ternali6able
Seriali!able //# is an interface that extends seriali!able interface and sends data into streams in compressed
format. $t has 9 methods writeE9ternal!ob&ectOtpt ot)5 readE9ternal!ob&ectInpt in)*
-xternali!able is an $nterface that extends Seriali!able $nterface. And sends data into Streams in
2ompressed Aormat. $t has two methods write-xternal(&b(ect&uput out) and read-xternal(&b(ect$nput in)
Q) Internalisation % Docali6ation
$nternalisation // )a'ing a programme to flexible to run in any locale called internalisation.
@ocali!ation // )a'ing a programme to flexible to run in a specific locale called @ocali!ation.
Q) (eriali6ation
Seriali!ation is the process of writing the state of the ob(ect to a byte streamM this is useful when ever you want
to save the state of your programme to a persistence storage area.
Q) (ynchroni6ation
Synchroni!ation is a process of controlling the access of shared resources by the multiple threads in such a
manner that only one thread can access one resource at a time. !Or) ,hen 9 are more threads need to access the
shared resources they need to some way ensure that the resources will be used by only one thread at a time. This
process which is achieved is called synchroni!ation.
(i) -x. / Synchroni!ing a function.
public synchroni!ed void )ethod> () L
N
(i) -x. / Synchroni!ing a bloc' of code inside a function.
public myAunction ()L
synchroni!ed (this) L
N
N
(iii) -x. / public Synchroni!ed void main(String argsOP)
Cut this is not the right approach because it means servlet can handle one re*uest at a time.
(iv) -x. / public Synchroni!ed void service()
Servlet handle one re*uest at a time in a serialized manner
Q) #ifferent level of loc)in$ sin$ (ynchroni6ation?
") 2lass level &b(ect level )ethod level Cloc' level
Q) 'onitor
A monitor is a mutex once a thread enter a monitor all other threads must wait until that thread exist the
monitor.
Q) #iff E E and *eFals!)?
") QQ 2ompare ob(ect references whether they refer to the sane instance are not.
e*uals () method compare the characters in the string ob(ect.
StringCuffer sb> Q new StringCuffer(KAmitK)M
StringCuffer sb9Q new StringCuffer(KAmitK)M
String s> Q KAmitKM
String s9 Q KAmitKM
String s< Q new String(KabcdK)M
String sU Q new String(KabcdK)M
String ss> Q KAmitKM
(sb>QQsb9)M A (s>.e*uals(s9))M T
(sb>.e*uals(sb9))M A ((s>QQs9))M T
(sb>.e*uals(ss>))M A (s<.e*uals(sU))M T
((s<QQsU))M A
String s> Q KabcKM
String s9 Q new String(KabcK)M
s> QQ s9 A
s>.e*uals(s9)) T

Q) 'ar)er Interfaces !or) +a$$ed Interfaces >.
An $nterface with no methods. $s called mar'er $nterfaces eg. Seriali!able SingleThread )odel 2loneable.
Q) 71D Encodin$ % 71D #ecodin$
RH@ -ncoding is the method of replacing all the spaces and other extra characters into their corresponding 1ex
2haracters and RH@ 3ecoding is the reverse process converting all 1ex 2haracters bac' their normal form.
Q) 71D % 71DConnection
RH@ is to identify a resource in a networ' is only used to read something from the networ'.
RH@ url Q new RH@(protocol name host name port url specifier)
RH@2onnection can establish communication between two programs in the networ'.
RH@ hp Q new RH@(5www.yahoo.com6)M
RH@2onnection con Q hp.open2onnection()M
Q) 1ntime class
Huntime class encapsulate the run/time environment. 8ou cannot instantiate a 1ntime ob(ect. 8ou can get a
reference to the current Huntime ob(ect by calling the static method 1ntime*$et1ntime!)
Huntime r Q Huntime.getHuntime()
@ong mem>M
)em> Q r.free)emory()M
)em> Q r.total)emory()M
Q) E9ecte other pro$rams
8ou can use (ava to execute other heavy weight process on your multi tas'ing operating system several form of
exec() method allow you to name the programme you want to run.
Huntime r Q Huntime.getHuntime()M
Process p Q nullM
TryL
p Q r.exce(5notepad6)M
p.waiAor()
N
Q) (ystem class
System class hold a collection of static methods and variables. The standard input output error output of the
(ava runtime are stored in the in5 ot5 err variables.
Q) -ative 'ethods
0ative methods are used to call subroutine that is written in a language other than (ava this subroutine exist as
executable code for the 2PR.
Q) Cloneable Interface
Any class that implements the cloneable interface can be cloned this interface defines no methods. $t is used to
indicate that a class allow a bit wise copy of an ob(ect to be made.
Q) Clone
4enerate a duplicate copy of the ob(ect on which it is called. 2loning is a dangerous action.
Q) Comparable Interface
2lasses that implements comparable contain ob(ects that can be compared in some meaningful manner. This
interface having one method compare the invo'ing ob(ect with the ob(ect. Aor sorting comparable interface will be used.
-x./ int compareTo(&b(ect ob()
Q) Class
2lass encapsulate the run/time state of an ob(ect or interface. )ethods in this class are
static 2lass for0ame(String name) throws
2lass0otAound-xception
get2lass()
get2lass@oader() get2onstructor()
getAield() get3eclaredAields()
get)ethods() get3ecleared)ethods()
get$nterface() getSuper2lass()
Q) &ava*&lan$*1eflect !pac)a$e)
Heflection is the ability of software to analyse it self to obtain information about the field constructor methods
T modifier of class. 8ou need this information to build software tools that enables you to wor' with (ava beans
components.
Q) InstanceOf
$nstanceof means by which your program can obtain run time type information about an ob(ect.
-x./ A a Q new A()M
a.instance&f AM
Q) Java pass ar$ments by vale are by reference?
") Cy value
Q) Java lac) pointers how do I implements classic pointer strctres li)e lin)ed list?
") Rsing ob(ect reference.
Q) &ava* E9e
)icro soft provided sd' for (ava which includes 5(exegentool6. This converts class file into a 5.-xec6 form. &nly
disadvantage is user needs a ).S (ava 7.) installed.
Q) 0in % Dib in &d)?
Cin contains all tools such as (avac appletviewer and awt tool.
@ib contains AP$ and all pac'ages.

Collections =rame Wor)
Q)
Collection classes Collection Interfaces De$acy classes De$acy interface
Abstract collection 2ollection 3ictionary -numerator
Abstract @ist @ist 1ash Table
Abstract Set Set Stac'
Array @ist Sorted Set 7ector
@in'ed @ist )ap Properties
1ash set $terator
Tree Set
1ash )ap
Tree )ap
Abstract Se*uential @ist
Collection Classes
"bstract collection $mplements most of the collection interfaces.
"bstract Dist -xtends Abstract collection T $mplements @ist $nterface. A.@ allow 5random access6.
Methods>> void add (int index, Object element), boolean add(Object o), boolean addll(Collection c), boolean
addll(int index, Collection c), Object remove(int index), void clear(), Iterator iterator()!
"bstract (et -xtends Abstract collection T $mplements Set interface.
"rray Dist Array @ist extends Abstract@ist and implements the @ist interface. Array@ist is a variable length of
array of ob(ect references Array@ist support dynamic array that grow as needed. A.@ allow rapid random access to
element but slow for insertion and deletion from the middle of the list. $t will allow dplicate elements* Searching is
very faster.
A.@ internal node traversal from the start to the end of the collection is significantly faster than @in'ed @ist traversal.
A.@ is a replacement for 7ector.
Methods>>void add (int index, Object element), boolean add(Object o), boolean addll(Collection c), boolean
addll(int index, Collection c), Object remove(int index), void clear(), object get(int index), int indexO"(Object
element), int latIndexO"(Object element), int si#e(), Object $% torray()!
Din)ed Dist -xtends AbstactSe*uential@ist and implements @ist interface. @.@ provide optimal se*uence access
in expensive insertion and deletion from the middle of the list relatively slow for random access. ,hen ever there is
a lot of insertion % deletion we have to go for @.@. @.@ is accessed via a reference to the first node of the list. -ach
subse*uent node is accessed via a reference to the first node of the list. -ach subse*uent node is accessed via the
lin'/reference number stored in the previous node.
Methods>> void add&irst(Object obj), add'ast(Object obj), Object get&irst(), Object get'ast(),void add (int index,
Object element), boolean add(Object o), boolean addll(Collection c), boolean addll(int index, Collection c),
Object remove(int index), Object remove(Object o), void clear(), object get(int index), int indexO"(Object element),
int latIndexO"(Object element), int si#e(), Object $% torray()!
<ash (et -xtends AbstractSet T $mplements Set interface it creates a collection that uses 1ashTable for
storage 1.S does not guarantee the order of its elements if u need storage go for TreeSet. $t will not allow
duplicate elements
Methods>>boolean add(Object o), Iterator iterator(), boolean remove(Object o), int si#e()!
+ree (et -xtends Abstract Set T $mplements Set interface. &b(ects are stored in sorted ascending order. Access
and retrial times are *uite fast. $t will not allow duplicate elements
Methods>> boolean add(Object o), boolean addll(Collection c), Object "irst(), Object last(), Iterator iterator(),
boolean remove(Object o)!
<ash 'ap -xtends Abstract )ap and implements )ap interface. 1.) does not guarantee the order of elements
so the order in which the elements are added to a 1.) is not necessary the order in which they are ready by the
iterate. 1.) permits only one nll vales in it while 1.T does not
1ash)ap is similar to 1ashtable.
+ree 'ap implements )ap interface a Tree)ap provides an efficient means of storing 'ey%value pairs in sorted
order and allow rapid retrieval.

"bstract (eFential Dist -xtends Abstract collectionM use se*uential access of its elements.
Collection Interfaces
Collection 2ollection is a group of ob(ects collection does not allow dplicate elements.
Methods >> boolean add(Object obj), boolean addll(c), int (i#e(), Object$% torray(), )oolean is*mpty(), Object $%
torray(), void clear().Collection c), Iterator iterator(),
boolean remove(Object obj), boolean removell(Collection
*xceptions >> +n(upported,ointer*xception, ClassCast*xception!
Dist @ist will extend 2ollection $nterface list stores a seFence of elements that can contain dplicates
elements can be accessed their position in the list using a !ero based index (it can access ob&ects by inde9).
Methods >> void add(int index, Object obj), boolean addll(int index, Collection c), Object get(int index), int
indexO"(Object obj), int lastIndexO"(Object obj), 'istIterator iterator(), Object remove(int index), Object
removell(2ollection c), Object set(int index, Object obj)!
(et Set will extend 2ollection $nterface Set cannot contain duplicate elements. Set stored elements in an
unordered way. (it can access ob&ects by vale).
(orted (et -xtends Set to handle sorted sets Sorted Set elements will be in ascending order.
Methods >> Object last(), Object "irst(), compactor compactor()!
*xceptions >> -ull,ointer*xception, ClassCast*xception, -o(uch*lement*xception!
'ap )ap maps uni*ue 'ey to value in a map for every 'ey there is a corresponding value and you will loo'up
the values using 'eys. )ap cannot contain dplicate 5'ey6 and 5value6. $n map both the 5key6 T 5value6 are
ob&ects.

Methods >> Object get(Object .) Object put(Object ., Object v) int si#e(), remove(Object object), boolean
is*mpty()
Iterator $terator ma'es it easier to traverse through the elements of a collection. $t also has an extra feature not
present in the older -numeration interface / the ability to remove elements. This ma'es it easy to perform a search
through a collection and strip out unwanted entries.
Cefore accessing a collection through an iterator you must obtain one if the collection classes provide an
iterator() method that returns an iterator to the start of the collection. Cy using iterator ob(ect you can access each
element in the collection one element at a time.
Methods >> boolean has-ext(), object next(),void remove()
-x./ Aray@ist arr Q new Array@ist()M
Arr.add(5c6)M
$terator itr Q arr.iterator()M
,hile(itr.hash0ext())
L
&b(ect element Q itr.next()M
N
Dist Iterator @ist $terator gives the ability to access the collection either forward%bac'ward direction
Legacy Classes
#ictionary is an abstract class that represent 'ey%value storage repository and operates much li'e 5)ap6 once
the value is stored you can retrieve it by using 'ey.
<ash +able 1ashTable stores 'ey%value pairs in hash table 1ashTable is synchronized when using hash table
you have to specify an object that is used as a .ey and the value that you want to lin'ed to that 'ey. The 'ey is then
hashed and the resulting hash code is used as the index at which the value is stored with the table. Rse 1.T to
store large amount of data it will search as fast as vector. 1.T store the data in se*uential order.
Methods>> boolean contains/ey(Object .ey), boolean contains0alue(Object value), Object get(Object .ey), Object
put(Object .ey, Object value)
(tac) is a sub class of vector stac' includes all the methods defined by vector and adds several of its own.
/ector 7ector holds any type of ob(ects it is not fixed length and vector is synchronized. ,e can store
primitive data types as well as ob&ects. 3efault length of vector is up to >?.
Methods>> "inal void add*lement(Object element), "inal int si#e(), "inal int capacity(), "inal boolean
remove*lementt(int index), "inal void removell*lements()!
Properties is a subclass of 1ashTable it is used to maintain the list of values in which the key!value" is
String#
Legacy Interfaces
Enmeration 3efine methods by which you can enumerate the elements in a collection of ob(ects. -numeration
is synchroni!ed.
Methods>> hasMore*lements(),Object next*lement()!
Q) Which is the preferred collection class to se for storin$ database reslt sets?
") @in'ed@ist is the best one benefits include.
>. Hetains the original retrieval order. 9. 1as *uic' insertion at the head%tail <. 3oesnJt have an internal si!e limitation
li'e a 7ector where when the si!e is exceeded a new internal structure is created. U. Permits user/controlled
synchroni!ation unli'e the pre/2ollections 7ector which is always synchroni!ed
HesultSet result Q stmt.executeYuery(K...K)M
@ist list Q new @in'ed@ist()M
while(result.next()) L
list.add(result.getString(KcolK))M
N
$f there are multiple columns in the result set youJll have to combine them into their own data structure for each row.
Arrays wor' well for that as you 'now the si!e though a custom class might be best so you can convert the contents to
the proper type when extracting from databse instead of later.
Q) Efficiency of <ash+able . If hash table is so fast5 why donGt we se it for everythin$?
") &ne reason is that in a hash table the relations among 'eys disappear so that certain operations (other than search
insertion and deletion) cannot be easily implemented. Aor example it is hard to traverse a hash table according to the
order of the 'ey. Another reason is that when no good hash function can be found for a certain application the time and
space cost is even higher than other data structures (array lin'ed list or tree).
1ashtable has two parameters that affect its efficiency. its capacity and its load factor. The load factor should be
between ?.? and >.?. ,hen the number of entries in the hashtable exceeds the product of the load factor and the
current capacity the capacity is increased by calling the rehash method. @arger load factors use memory more
efficiently at the expense of larger expected time per loo'up.
$f many entries are to be put into a 1ashtable creating it with a sufficiently large capacity may allow the entries to be
inserted more efficiently than letting it perform automatic rehashing as needed to grow the table.
Q) <ow does a <ashtable internally maintain the )ey.vale pairs?
") The 1ashtable class uses an internal (private) class named -ntry to hold the 'ey/value pairs. All entries of the
1ashtable are stored in an array of -ntry ob(ects with the hash value of the 'ey serving as the index. $f two or more
different 'eys have the same hash value these entries are stored as a lin'ed list under the same index.
Q) "rray
Array of fixed length of same data typeM we can store primitive data types as well as class ob(ects.
Arrays are initiali!ed to the default value of their type when they are created not declared even if they are local
variables
Q) #iff Iterator % Enmeration % Dist Iterator
$terator is not synchroni!ed and enumeration is synchroni!ed. Coth are interface $terator is collection interface
that extends from E@istG interface. -numeration is a legacy interface -numeration having 9 methods ECoolean
has)ore-lements()G T E&b(ect 0ext-lement()G. $terator having < methods Eboolean has0ext()G Eob(ect next()G Evoid
remove()G. $terator also has an extra feature not present in the older -numeration interface / the ability to remove
elements there is one method 5void remove()6.
Dist Iterator
$t is an interface @ist $terator extends $terator to allow bi/directional traversal of a list and modification of the
elements. )ethods are Ehas0ext()G E hasPrevious()G.
Q) #iff <ash+able % <ash'ap
Coth provide 'ey%value to access the data. The 1.T is one of the collection original collection classes in (ava. 1.P is
part of new collection framewor'.
1.T is synchroni!ed and 1.) is not.
1.) permits null values in it while 1.T does not.
$terator in the 1.P is fail/safe while the enumerator for the 1.T is not.
Q) Convertin$ from a Collection to an array . and bac) a$ain?
The collection interface define the toArray() method which returns an array of ob(ects. $f you want to convert bac' to a
collection implementation you could manually traverse each element of the array and add it using the add(&b(ect)
method.
%% 2onvert from a collection to an array
&b(ectOP array Q c.toArray()M
%% 2onvert bac' to a collection
2ollection c9 Q new 1ashSet()M
for(int i Q ?M i " array.lengthM iSS)
L
c9.add(arrayOiP)M
N
Q) <ow do I loo) thro$h each element of a <ash'ap?
") "select idQKswfK nameQKswfK on2hangeQKshowStandard,A()K styleQKwidth.>DBpxMK#
"option valueQKK#TltMSelect Standard ,or'AlowTgtM"%option#
"Z
hmap Q(1ash)ap)re*uest.getAttribute(KstdwfK)M
if( hmap.si!e() WQ ?)L
int len Q hmap.si!e()M
Set set Q hmap.'eySet()M
$terator it Q set.iterator()M
while(it.has0ext())
L
$nteger 'ey Q ($nteger)it.next()M
Z#
"option valueQK"ZQ'eyZ#K#"ZQ(String)hmap.get('ey)Z#"%option#
"Z
N
N
Z#
"%select#
Q) 1etrievin$ data from a collection?
public class $terator3emo
L
public static void main(String argsOP)
L
2ollection c Q new Array@ist()M
%% Add every parameter to our array list
for (int indx Q ?M indx " args.lengthM indxSS)
L
c.add(argsOindxP)M
N
%% -xamine only those parameters that start with /
$terator i Q c.iterator()M
%% PH- . 2ollection has all parameters
while (i.has0ext())
L
String param Q (String) i.next()M
%% Rse the remove method of iterator
if (W param.starts,ith(K/K) )
i.remove()M
N
%% P&ST. 2ollection only has parameters that start with /
%% 3emonstrate by dumping collection contents
$terator i9 Q c.iterator()M
while (i9.has0ext())
L
System.out.println (KParam . K S i9.next())M
N
N
N
Q) <ow do I sort an array?
") Arrays class provides a series of sort() methods for sorting arrays. $f the array is an array of primitives (or) an array
of a class that implements 2omparable then you can (ust call the method directly.
Arrays.sort(theArray)M
$f however it is an array of ob&ects that donJt implement the 2omparable interface then you need to provide a custom
2omparator to help you sort the elements in the array.
Arrays.sort(theArray the2omparator)M
EEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEE
E9ception <andlin$
Ob&ect

+hrowable
Error E9ception
"W+ Error /irtal 'achine Error
Compile time*E9 1ntime E9ception
!chec)ed) !7nchec)ed)
OtOf'emory*E (tac)Over=low*E EO=*E =ilenot=ond*E
"rithmetic*E -llPointer*E Inde9otof
0ond*E
"rrayInde9otOf0ond*E (tirn$Inde9otOf0ond
Q) #iff E9ception % Error
-xception and -rror both are subclasses of the Throwable class.

E9ception-xception is generated by (ava runtime system (or) by manually. An exception is a abnormal condition that
transfer program execution from a thrower to catcher.
Error ,ill stop the program execution -rror is a abnormal system condition we cannot handle these.
Q) Can an e9ception be rethrown?
A) 8es an exception can be rethrown.
Q) try5 catch5 throw5 throws
try This is used to fix up the error to prevent the program from automatically terminating try/catch is used to
catching an exception that are thrown by the (ava runtime system.
Throw is used to throw an exception explicitly.
Throws A Throws clause list the type of exceptions that a methods might through.
Q) What happens if an e9ception is not ca$ht?
A) An uncaught exception results in the uncaught-xception() method of the threadJs Thread4roup being invo'ed which
eventually results in the termination of the program in which it is thrown.
Q) What happens if a try.catch.finally statement does not have a catch clase to handle an e9ception that is
thrown within the body of the try statement?
The exception propagates up to the next higher level try/catch statement (if any) or results in the programJs termination.
Q) Chec)ed % 7nChec)ed E9ception >.
2hec'ed exception is some subclass of -xception. )a'ing an exception chec'ed forces client programmers to
deal with the possibility that the exception will be thrown. eg $&-xception thrown by (ava.io.Aile$nputStreamJs read()
method[

Rnchec'ed exceptions are Huntime-xception and any of its subclasses. 2lass -rror and its subclasses also are
unchec'ed. ,ith an unchec'ed exception however the compiler doesnJt force client programmers either to catch the
exception or declare it in a throws clause. $n fact client programmers may not even 'now that the exception could be
thrown. eg String$ndex&ut&fCounds-xception thrown by StringJs charAt() method[ 2hec'ed exceptions must be caught
at compile time. Huntime exceptions do not need to be. -rrors often cannot be.
Chec)ed E9ceptions 7n chec)ed e9ception
2lass0otAound-xception Arithmetic-xception
0oSuch)ethod-xception Array$ndex&ut&fCound-xception
0oSuchAield-xception 2lasscast-xception
$nterrupted-xception $llegalArgument-xception
$llegalAccess-xception $llegal)onitorSate-xception
2lone0otSupported-xception $llegalThreadState-xception
$ndex&ut&fCound-xception
0ullPointer-xception
0umberAormat-xception
String$ndex&ut&fCounds
OtOf'emoryError ..C Signals that J7) has run out of memory and that the garbage collector is unable to claim
any more free memory.
(tac)Over=low ..C Signals that a stac' &.A in the interpreter.
"rrayInde9OtOfbond ..C Aor accessing an array element by providing an index values "? or # or e*ual to the
array si!e.
(trin$Inde9OtOfbond ..C Aor accessing character of a string or string buffer with index values "? or # or
e*ual to the array si!e.
"rithmetic E9ception ..C such as divide by !ero.
"rray(tore E9ception ..C Assignment to an array element of an incompatible types.
ClasscastE9ception ..C $nvalid casting.
Ille$al"r$ment E9ception ..C $llegal argument is used to invo'e a method.
-llpointer E9ception ..C $f attempt to made to use a null ob(ect.
-mber=ormat E9ception ..C $nvalid conversition of string to numeric format.
Class-otfond E9ception ..C class not found.
Instantion E9ception ..C Attempt to create an ob(ect of an Abstract class or $nterface.
-osch=ield E9ception ..C A re*uest field does not exist.
-osch'ethod E9ception ..C A re*uest method does not exist.
Q) 'ethods in E9ceptions?
") get)essage() toString() printStac'Trace() get@ocali!ed)essage()
Q) What is e9ception chainin$?
") An exception chain is a list of all the exceptions generated in response to a single root exception. As
each exception is caught and converted to a higher/level exception for rethrowing itJs added to the chain.
This provides a complete record of how an exception is handled The chained exception AP$ was introduced in >.U. Two
methods and two constructors were added to Throwable.
Throwable get2ause()
Throwable init2ause(Throwable)
Throwable(String Throwable)
Throwable(Throwable)
The Throwable argument to init2ause and the Throwable constructors is the exception that caused the current
exception. get2ause returns the exception that caused the current exception and init2ause returns the current
exception.
Q) Primitive mlti tas)in$
$f the threads of different priorities shifting the control depend on the priority i.e.M a thread with higher priority is
executed first than the thread with lower priority. This process of shifting control is 'nown as primitive multi tas'ing.
Q) <ttp (tats Codes
To inform the client of a problem at the server end you call the 5send-rror6 method. This causes the server to
respond with status line with protocol version and a success or error code.
The first digit of the status code defines the class of response while the last two digits do not have categories
Number $ype %escription
>xx $nformational He*uested received continuing to process
9xx Success The action was successfully received understood and accepted
<xx Hedirection Aurther action must be ta'en in order to complete the re*uest
Uxx 2lient -rror The re*uest contains bad syntax or cannot be fulfilled
Bxx Server -rror The server failed to fulfil valid re*uest
"ll Pac)a$es
Q) +hread Class
)ethods. /
get0ame() run()
getPriority() Sleep()
isAlive() Start()
(oin()
Q) Ob&ect class
All other classes are sub classes of ob(ect class &b(ect class is a super class of all other class.
)ethods. /
void notify() void notifyAll()
&b(ect clone() Sting toString()
boolean e*uals(&b(ect ob(ect) void wait()
void finali!e() void wait(long milliseconds int nanoseconds)
int hashcode()
Q) throwable class
)ethods. /
String get)essage() 7oid printStac'Trace()
String toString() Throwable fill$nStac'Trace()
Q) Java9*servlet Pac)a$e
Interfaces Classes &'ceptions
Servlet 4enericServlet Servlet-xception
Servlet2onfig Servlet$nputStream Rnavaliable-xception
Servlet2ontext Servlet&utputStream
ServletHe*uest (ervletConte9t"ttribteEvent
ServletHesponse
SingleThread)odel
(ervletConte9tDistener
(ervletConte9t"ttribteDistener
(ervletConte9tInitiali6ation parameters
(ervlet1eFest"ttribteDistener
(ervlet1eFestDistner
=ilter
=ilterChain
=ilterConfi$
1eFest#ispatcher
4enericServlet (2) public void destroy()M
public String get$nitParameter(String name)M
public -numeration get$nitParameter0ames()M
public Servlet2onfig getServlet2onfig()M
public Servlet2ontext getServlet2ontext()M
public String getServlet$nfo()M
public void init(Servlet2onfig config) throws Servlet-xceptionM
public void log(String msg)M
public abstract void service(ServletHe*uest re* ServletHesponse res)
Servlet$nputStream (2) public int read@ine(byte bOP int off int len)
Servlet&utputStream (2) public void print(String s) throws $&-xceptionM
public void println() throws $&-xceptionM
Servlet2ontextAttribute-vent (2) public void attribte"dded(Servlet2ontextAttribute-vent scab)
public void attribte1emoved(Servlet2ontextAttribute-vent scab)
public void attribte1eplaced(Servlet2ontextAttribute-vent scab)
Servlet ($) public abstract void destroy()M
public abstract Servlet2onfig getServlet2onfig()M
public abstract String getServlet$nfo()M
public abstract void init(Servlet2onfig config) throws Servlet-xceptionM
public abstract void service(ServletHe*uest re* ServletHesponse res)
Servlet2onfig ($) public abstract String get$nitParameter(String name)M
public abstract Enmeration get$nitParameter0ames()M
public abstract Servlet2ontext getServlet2ontext()M
Servlet2ontext ($) public abstract &b(ect getAttribute(String name)M
public abstract String getHealPath(String path)M
public abstract String getServer$nfo()M
public abstract Servlet getServlet(String name) throws Servlet-xceptionM
public abstract -numeration getServlet0ames()M
public abstract -numeration getServlets()M
public abstract void log(-xception exception String msg)M
ServletHe*uest ($) public abstract &b(ect getAttribute(String name)M
public abstract String getParameter(String name)M
public abstract Enmeration getParameter0ames()M
public abstract StringOP getParameter7alues(String name)M
public abstract String getHealPath(String path)M
public abstract String getHemoteAddr()M
public abstract String getHemote1ost()M
public abstract String getServer0ame()M
public abstract int getServerPort()M
1eFest#ispatcher $et1eFest#ispatcher!(trin$ path),
pblic int $etDocalPort!), %% servlet @*H
pblic int $et1emotePort!), %% servlet @*H
pblic (trin$ $etDocal-ame!), %% servlet @*H
pblic (trin$ $etDocal"ddr!), %% servlet @*H
ServletHesponse ($) public abstract String get2haracter-ncoding()M
public abstract Print,riter get,riter() throws $&-xceptionM
public abstract void set2ontent@ength(int len)M
public abstract void set2ontentType(String type)M
Q) Java9*servlet*<ttp Pac)a$e
Interfaces Classes &'ceptions
1ttpServletHe*uest 2oo'ies Servlet-xception
1ttpServletHesponse 1ttpServlet (Abstarct 2lass) Rnavaliable-xception
1ttpSession 1ttpRtils
<ttp(essionDistener <ttp(ession0indin$Event
<ttp(ession"ctivationDistener
<ttp(ession"ttribteDistener
<ttp(ession0indin$Distener
1ttpSession2ontext (deprecated)
Ailter
(ervletConte9tDistener !I) pblic void conte9tInitiali6ed!(ervletConte9tEvent event)
pblic void conte9t#estroyed!(ervletConte9tEvent event)
(ervletConte9t"ttribteDistener !I) public void attributeAdded(Servlet2ontextAttribute-vent scab)
public void attributeHemoved(Servlet2ontextAttribute-vent scab)
public void attributeHeplaced(Servlet2ontextAttribute-vent scab)
(ervletConte9tInitila6ation parameters
Coo)ies !C) public &b(ect clone()M
public int get)axAge()M
public String get0ame()M
public String getPath()M
public String get7alue()M
public int get7ersion()M
public void set)axAge(int expiry)M
public void setPath(String uri)M
public void set7alue(String new7alue)M
public void set7ersion(int v)M
<ttp(ervlet !C) public void service(ServletHe*uest req, ServletResponse res)
protected void do3elete (1ttpServletHe*uest re* 1ttpServletHesponse res)
protected void do4et (1ttpServletHe*uest re* 1ttpServletHesponse res)
protected void do&ptions(1ttpServletHe*uest re* 1ttpServletHesponse res)
protected void doPost(1ttpServletHe*uest re* 1ttpServletHesponse res)
protected void doPut(1ttpServletHe*uest re* 1ttpServletHesponse res)
protected void doTrace(1ttpServletHe*uest re* 1ttpServletHesponse res)
protected long get@ast)odified(1ttpServletHe*uest re*)M
protected void service(1ttpServletHe*uest re* 1ttpServletHesponse res)
<ttp(essionbindin$Event !C) public String get0ame()M
public 1ttpSession getSession()M
<ttp(ervlet1eFest !I) public abstract 2oo'ieOP get2oo'ies()M
public abstract String get1eader(String name)M
public abstract -numeration get1eader0ames()M
public abstract String getYueryString()M
public abstract String getHemoteRser()M
public abstract String getHe*uestedSession$d()M
public abstract String getHe*uestRH$()M
public abstract String getServletPath()M
public abstract 1ttpSession getSession(boolean create)M
public abstract boolean isHe*uestedSession$dArom2oo'ie()M
public abstract boolean isHe*uestedSession$dAromRrl()M
public abstract boolean isHe*uestedSession$d7alid()M
<ttp(ervlet1esponse !I) public abstract void add2oo'ie(2oo'ie coo'ie)M
public abstract String encodeHedirectRrl(String url)M
public abstract String encodeRrl(String url)M
public abstract void send-rror(int sc String msg) throws $&-xceptionM
public abstract void sendHedirect(String location) throws $&-xceptionM
pblic abstract void addInt<eader!(trin$ header5 int vale),
pblic abstract void add#ate<eader!(trin$ header5 lon$ vale),
public abstract void set1eader(String name String value)M
pblic abstract void setInt<eader!(trin$ header5 int vale),
pblic abstract void set#ate<eader!(trin$ header5 lon$ vale),
public void setStatus()M
<ttp(ession !I) public abstract long get2reationTime()M
public abstract String get$d()M
public setAttribute(String name &b(ect value)M
public getAttribute(String name &b(ect value)M
public remove Attribute(String name &b(ect value)M
public abstract long get@astAccessedTime()M
public abstract 1ttpSession2ontext getSession2ontext()M
public abstract &b(ect get7alue(String name)M
public abstract StringOP get7alue0ames()M
public abstract void invalidate()M
public abstract boolean is0ew()M
public abstract void put7alue(String name &b(ect value)M
public abstract void remove7alue(String name)M
public set)ax$nactive$ntervel()M
<ttp(essionDistener !I) public void session2reated(1ttpSession-vent event)
public void session3estroyed(1ttpSession-vent event)
<ttp(ession"ttribteDistener !I) public void attributeAdded(Servlet2ontextAttribute-vent scab)
public void attributeHemoved(Servlet2ontextAttribute-vent scab)
public void attributeHeplaced(Servlet2ontextAttribute-vent scab)
<ttp(ession0indin$Distener !I)
public void 1ttpSessionCinding@istener.valueCound(1ttpSessionCinding-vent event)
public void 1ttpSessionCinding@istener.valueRnbound(1ttpSessionCinding-vent event)
<ttp(ession"ctivationDistener !I)
public void session3idActivate(1ttpSession-vent event)
public void session,illpassivate(1ttpSession-vent event)
=ilter !i)
public void doAilter (ServletHe*uest re*uest ServletHesponse response Ailter2hain chain)
public Ailter2onfig getAilter2onfig()
public void setAilter2onfig (Ailter2onfig filter2onfig)
Q) &ava*sFl Pac)a$e
Interfaces Classes &'ceptions
2onnection 3river)anager
2allableStatement 3ate 2lass0otAound-xception
3river TimeStamp $nstantiation -xception
PreparedStatement Time
HesultSet Types
HesultSet)eta3ata SY@ -xception SY@
,arnings
Statement
3atabase)eta3ata
Array
Parameter'eta#ata
2lob Clob
SY@$nput SY@&utput SY@Permission
(avepoint
Q) &ava9*sFl Pac)a$e
Interfaces Classes &'ceptions
ConnectionEventDistener ConnectionEvent
ConnectionPool#ata(orce 1owsetEvent
#ata(orce
PooledConnection
1ow(et
1ow(etDistener
1ow(et'eta#ate
1ow(et1eaderIWriter
J"Connection
J"#ata(orce
Q) &ava*lan$ Pac)a$e
Interfaces Classes &'ceptions
2loneable 3ouble Aloat @ong $nteger Short
Cyte Coolean 2haracter
Arithmetic-xception
Array$ndex&ut&fCound&f.-
2lass2ast.- 2lass0otAound.-
Hunnable 2lass 2lass@oader $lleAcess.- $llegalArgument.-
2omparable Process HunTime 7oid $llegalSate.- 0ullPointer.-
String StringCuffer 0oSuchAield.- 0oSuch)ethod.-
Thread Thread4roup 0umberAormat.-
Q) &ava*IO Pac)a$e
Interfaces Classes &'ceptions
3ata$nputstream Cuffer$nputstream Cuffer&utputStream
3ata&utputstream CufferHeader Cuffer,riter
&b(ect$nputStream CyteArray$nputStream CyteArray&utputstream
&b(ect&utputstream 2haracterarrayHeader 2haracterAray,riter
Seriali!able 3ata$nputStream 3ata&utputStream
-xterniali!able Ailereader Aile,riter
&b(ect$nputStream &b(ect&utputStream
(E1/DE+ Qestions
Class path. /
set pathQ c.F(9sd'>.U.9Fbin
set classpathQ c.F (9sd'>.U.9FlibFtools.(arMc.Fservlet.(ar
2.FTomcatBFbinFstartup.bat shortcut
Q) (ervlet
Servlet is server side component a servlet is small plug gable extension to the server and servlets are used to
extend the functionality of the (ava/enabled server. Servlets are durable ob(ects means that they remain in memory
specially instructed to be destroyed. Servlets will be loaded in the Address space of web server.
Servlet are loaded < ways >) ,hen the web sever starts 9) 8ou can set this in the configuration file <) Through an
administration interface.
Q) What is +emporary (ervlet?
") ,hen we sent a re*uest to access a JSP servlet container internally creates a JservletJ T executes it. This servlet is
called as JTemporary servletJ. $n general this servlet will be deleted immediately to create T execute a servlet base on a
JSP we can use following command.
Java weblogic.(spc\'eepgenerated X.(sp
Q) What is the difference between (erver and Container?
") A server provides many services to the clients A server may contain one or more containers such as e(b containers
servlet%(sp container. 1ere a container holds a set of ob(ects.
Q) (ervlet Container
The servlet container is a part of a ,eb server (or) Application server that provides the networ' services over
which re*uests and responses are sent decodes )$)-/based re*uests and formats )$)-/based responses. A servlet
container also contains and manages servlets through their lifecycle.
A servlet container can be built into a host ,eb server or installed as an add/on component to a ,eb Server via that
serverGs native extension AP$. All servlet containers must support 1TTP as a protocol for re*uests and
responses but additional re*uest%response/based protocols such as 1TTPS (1TTP over SS@) may be supported.
Q) 8enerally (ervlets are sed for complete <+'D $eneration* If yo want to $enerate partial <+'DGs that
inclde some static te9t as well as some dynamic te9t5 what method do yo se?
") Rsing JHe*uest3ispather.include(5xx.html6) in the servlet code we can mix the partial static 1T)@ 3irectory page.
-x. / He*uest3ispatcher rdQServlet2ontext.getHe*uest3ispatcher(5xx.html6)M
rd.include(re*uestresponse)M
Q) (ervlet Dife cycle
Public void init (Servlet2onfig config) throws Servlet-xception
public void service (ServletHe*uest re* ServletHesponse res) throws Servlet-xception $&-xception
public void destroy ()
The ,eb server when loading the servlet calls the init method once. (The init method typically establishes database
connections.)
Any re*uest from client is handled initially by the service () method before delegating to the do*'' () methods in the
case of 1ttpServlet. $f u put 5Private; modifier for the service() it will give compile time error.
,hen your application is stopped (or) Servlet 2ontainer shuts down your ServletJs destroy !) method will be called.
This allows you to free any resources you may have got hold of in your ServletJs init () method this will call only once.
(ervletE9ception Signals that some error occurred during the processin$ of the re*uest and the container should
ta'e appropriate measures to clean up the re*uest.
IOE9ception Signals that Servlet is unable to handle re*uests either temporarily or permanently.
Q) Why there is no constrctor in servlet?
") A servlet is (ust li'e an applet in the respect that it has an init() method that acts as a constructor an initiali!ation
code you need to run should e place in the init() since it get called when the servlet is first loaded.
Q) Can we se the constrctor5 instead of init!)5 to initiali6e servlet?
") 8es of course you can use. ThereGs nothing to stop you. Cut you shouldnGt. The original reason for init() was that
ancient versions of Java couldnGt dynamically invo'e constructors with arguments so there was no way to give the
constructur a Servlet2onfig. That no longer applies but servlet containers still will only call your no/arg constructor. So
you wonGt have access to a Servlet2onfig or Servlet2ontext.
Q) Can we leave init!) method empty and insted can we write initili6ation code inside servletGs constrctor?
") 0o because the container passes the Servlet2onfig ob(ect to the servlet only when it calls the init method. So
Servlet2onfig will not be accessible in the constructor.
Q) #irectory (trctre of Web "pplications?
") ,ebApp%(Publicly available files such as
] .(sp .html .(pg .gif)
]
S,-C/$0A%/S
]
S classes%(Java classes (ervlets)
]
S lib%(&ar files)
]
S web*9ml I !ta$lib*tld)
]
S weblogic.xml

,AH/# ,AHfile can be placed in a serverGs webapps directory
Q) Web*9ml> .
"web/app#
BK.. #efines Web"pp initiali6ation parameters*..C
"context/param#
"param/name#locale"%param/name#
"param/value#RS"%param/value#
"%context/param#
BK.. #efines filters and specifies filter mappin$ ..C
"filter#
"filter/name#Test Ailter"%filter/name#
"filter/class#filters.TestAilter"%filter/class#
"init/param#
"param/name#locale"%param/name#
"param/value#RS"%param/value#
"%init/param#
"%filter#
"filter/mapping#
"filter/name#Test Ailter"%filter/name#
"servlet/name#TestServlet"%servlet/name#
"%filter/mapping#
BK.. #efines application events listeners ..C
"listener#
"listener/class#
listeners.)yServlet2ontext@istener"%listener/class#
"%listener#
"listener#
"listener/class#
listeners.)ySession2um2ontext@istener
"%listener/class#
"%listener#
BK.. #efines servlets ..C
"servlet#
"servlet/name#1elloServlet"%servlet/name#
"servlet/class#servlets.1elloServlet"%servlet/class#
"init/param#
"param/name#driverclassname"%param/name#
"param/value#sun.(dbc.odbc.Jdbc&dbc3river"%param/value#
"%init/param#
"init/param#
"param/name#dburl"%param/name#
"param/value#(dbc.odbc.)ySY@&3C2"%param/value#
"%init/param#
"security/role/ref#
BK.. role.name is sed in <ttp(ervlet1eFest*is7serIn1ole!(trin$ role) method* ..C
"role/name#manager"%role/name#
BK.. role.lin) is one of the role.names specified in secrity.role elements* ..C
"role/lin'#supervisor"%role/lin'#
"%security/role/ref#
"%servlet#
BK.. #efines servlet mappin$s ..C
"servlet/mapping#
"servlet/name#1elloServlet"%servlet/name#
"url/pattern#X.hello"%url/pattern#
"%servlet/mapping#
BK..specifies session timeot as AL mintes* ..C
"session/config#
"session/timeout#<?"%session/timeout#
"session/config#
"welcome/file/list#
"welcome/file#index.html"%welcome/file#
"%welcome/file/list#
"W // Error pa$e // #
"error/page#
"error/code#U?U"%error/code#
"location#notfoundpage.(sp"%location#
"%error/page#
"error/page#
"exception/type#(ava.s*l.SY@-xception"%exception/type#
"location#s*lexception.(sp"%location#
"%error/page#
"taglib#
"taglib/uri#http.%%abc.com%testlib"%taglib/uri#
"taglib/location#%,-C/$0A%tlds%testlib.tld"%taglib/location#
"%taglib#
"taglib#
"taglib/uri#%examplelib"%taglib/uri#
"taglib/location#%,-C/$0A%tlds%examplelib.tld"%taglib/location#
"%taglib#
BK.. only PO(+ method is protected ..C
"http/method#P&ST"%http/method#
"web/resource/collection#
"web/resource/name#Another Protected Area"%web/resource/name#
"url/pattern#X.hello"%url/pattern#
"%web/resource/collection#
BK.. ath.method can be> 0"(IC5 =O1'5 #I8E(+5 or CDIE-+.CE1+ ..C
"auth/method#A&H)"%auth/method#
"realm/name#sales"%realm/name#
"form/login/config#
"form/login/page#%formlogin.html"%form/login/page#
"form/error/page#%formerror.(sp"%form/error/page#
"%form/login/config#
"%login/config#
"%web/app#
Q) "tomatically start (ervlet?
") $f present calls the servletJs service() method at the specified times. "run/at# lets servlet writers execute periodic
tas's without worrying about creating a new Thread.
The value is a list of 9U/hour times when the servlet should be automatically executed. To run the servlet every ; hours
you could use.
"servlet servlet/nameQJtest.1ello,orldJ#
"run/at#?.?? ;.?? >9.?? >^.??"%run/at#
"%servlet#
Q) (ervletConfi$ Interface % (ervletConte9 Interfaces
(ervletConfi$ Servlet2onfig ob(ect is used to obtain configuration data when it is loaded. There can be multiple
Servlet2onfig ob(ects in a single web application.
This ob(ect defines how a servlet is to be configured is passed to a servlet in its init method. )ost servlet
containers provide a way to configure a servlet at run/time (usually through flat file) and set up its initial parameters. The
container in turn passes these parameters to the servlet via the Servet2onfig.
E9>.
"web/app#
"servlet#
"servlet/name#TestServlet"%servlet/name#
"servlet/class#TestServlet"%servlet/class#
"init/param#
"param/name#driverclassname"%param/name#
"param/value#sun.(dbc.odbc.Jdbc&dbc3river"%param/value#
"%init/param#
"init/param#
"param/name#dburl"%param/name#
"param/value#(dbc.odbc.)ySY@&3C2"%param/value#
"%init/param#
"%servlet#
"%web/app#
......................................
public void init()
L
Servlet2onfig config Q $et(ervletConfi$!)M
String driver2lass0ame Q config.get$nitParameter(KdriverclassnameK)M
String dbRH@ Q config.get$nitParameter(KdburlK)M
2lass.for0ame(driver2lass0ame)M
db2onnection Q 3river)anager.get2onnection(dbRH@usernamepassword)M
N
(ervletConte9t Servlet2ontext is also called application ob+ect. Servlet2ontext is used to obtain information about
environment on which a servlet is running.
There is one instance ob(ect of the Servlet2ontext interface associated with each ,eb application deployed into a
container. $n cases where the container is distributed over many virtual machines a ,eb application will have an
instance of the Servlet2ontext for each J7).
Servlet 2ontext is a grouping under which related servlets run. They can share data RH@ namespace and other
resources. There can be multiple contexts in a single servlet container.
Q) <ow to add application scope in (ervlets?
") $n Servlets Application is nothing but Servlet2ontext Scope.
Servlet2ontext app2ontext Q servlet2onfig.getServlet2ontext()M
app2ontext.setAttribute(param0ame re*.getParameter(param0ame))M
app2ontext.getAttribute(param0ame)M
Q) #iff between <ttp(eassion % (tatefl (ession bean? Why canGt <ttp(essionn be sed instead of of (ession
bean?
") 1ttpSession is used to maintain the state of a client in webservers which are based on 1ttp protocol. ,here as
Stateful Session bean is a type of bean which can also maintain the state of the client in Application servers based on
H)$/$$&P.
Q) Can we store ob&ects in a session?
") session.setAttribute(Kproduct$ds$n2artKproduct$ds$n2art)M
session.removeAttribute(Kproduct$ds$n2artK)M
Q) (ervlet Disteners
!i) (ervletConte9tDistener
void conte9t#estroyed (Servlet2ontext-vent sce)
void conte9tInitiali6ed (Servlet2ontext-vent sce)
$mplementations of this interface receive notifications about changes to the servlet context of the web
application they are part of. To receive notification events the implementation class must be configured in the
deployment descriptor for the web application.
!ii) (ervletConte9t"ttribteDistener !I)
void attribte"dded (Servlet2ontextAttribute-vent scab)
void attribte1emoved (Servlet2ontextAttribute-vent scab)
void attribte1eplaced (Servlet2ontextAttribute-vent scab)
$mplementations of this interface receive notifications of changes to the attribute list on the servlet context of a
web application. To receive notification events the implementation class must be configured in the deployment
descriptor for the web application.
Q) <ttpDisteners
!i) <ttp(essionDistener !I)
public void sessionCreated(1ttpSession-vent event)
public void session#estroyed(1ttpSession-vent event)
$mplementations of this interface are notified of changes to the list of active sessions in a web application. To
receive notification events the implementation class must be configured in the deployment descriptor for the web
application.
!ii) <ttp(ession"ctivationDistener !I)
public void sessionWillPassivate(1ttpSession-vent se)
public void session#id"ctivate(1ttpSession-vent se)
&b(ects that are bound to a session may listen to container events notifying them that sessions will be
passivated and that session will be activated.
!iii) <ttp(ession"ttribteDistener !I)
public void attribte"dded(1ttpSessionCinding-vent se)
public void attribte1emoved(1ttpSessionCinding-vent se)
public void attribte1eplaced(1ttpSessionCinding-vent se)
This listener interface can be implemented in order to get notifications of changes to the attribute lists of
sessions within this web application.
!iv) <ttp(ession 0indin$ Distener !MM If session will e9pire how to $et the vales)
Some ob(ects may wish to perform an action when they are bound (or) unbound from a session. Aor example a
database connection may begin a transaction when bound to a session and end the transaction when unbound. Any
ob(ect that implements the (avax.servlet.http.1ttpSessionCinding@istener interface is notified when it is bound (or)
unbound from a session. The interface declares two methods valueCound() and valueRnbound() that must be
implemented.
Methods1 2
public void 1ttpSessionCinding@istener.vale0ond(1ttpSessionCinding-vent event)
public void 1ttpSessionCinding@istener.vale7nbond(1ttpSessionCinding-vent event)
valueCound() method is called when the listener is bound into a session
valueRnbound() is called when the listener is unbound from a session.
The (avax.servlet.http.1ttpSessionCinding-vent argument provides access to the name under which the ob(ect is being
bound (or unbound) with the get0ame() method.
public String 1ttpSessionCinding-vent.get0ame()
The 1ttpSessionCinding-vent ob(ect also provides access to the 1ttpSession ob(ect to which the listener is being bound
(or unbound) with getSession() .
public 1ttpSession 1ttpSessionCinding-vent.getSession()
QQQQQQQQQ
public class SessionCindings extends 1ttpServlet L
public void do4et(1ttpServletHe*uest re* 1ttpServletHesponse res)
throws Servlet-xception $&-xception L
res.set2ontentType(Ktext%plainK)M
Print,riter out Q res.get,riter ()M
1ttpSession session Q re*.getSession(true)M
session.put7alue(Kbindings.listenerK
new 2ustomCinding@istener(getServlet2ontext()))M %% Add a 2ustomCinding@istener
N
N
QQQQQQQQQQQQQ
class 2ustomCinding@istener implements 1ttpSessionCinding@istener
L
Servlet2ontext contextM
public 2ustomCinding@istener(Servlet2ontext context) L
this.context Q contextM
N
public void valueCound(1ttpSessionCinding-vent event) L
context.log(KC&R03 as K S event.get0ame() S K to K S event.getSession().get$d())M
N
public void valueRnbound(1ttpSessionCinding-vent event) L
context.log(KR0C&R03 as K S event.get0ame() S K from K S event.getSession().get$d())M
N
N
Q) =ilter
&ilter is an ob(ect that intercepts a message between a data source and a data destination and then filters the data
being passed between them. $t acts as a guard preventing undesired information from being transmitted from one point
to another.
,hen a servlet container receives a re*uest for a resource it chec's whether a filter is associated with this resource. $f
a filter is associated with the resource the servlet container routes the re*uest to the filter instead of routing it to the
resource. The filter after processing the re*uest does one of three things.
_ $t generates the response itself and returns it to the client.
_ $t passes on the re*uest (modified or unmodified) to the next filter in the chain
_ $t routes the re*uest to a different resource.
E9amples of =ilterin$ Components
_ Authentication filters _ @ogging and auditing filters _ $mage conversion filters _ 3ata compression filters
_ -ncryption filters _ To'eni!ing filters _ Ailters that trigger resource access events
_ )$)-/type chain filters _ 2aching filters _ `S@%T filters that transform `)@ content
The (avax.servlet.Ailter interface defines three methods.
public void doAilter (ServletHe*uest re*uest ServletHesponse response Ailter2hain chain)
public Ailter2onfig getAilter2onfig()
public void setAilter2onfig (Ailter2onfig filter2onfig)
E9>.
public class SimpleAilter implements Ailter
L
private Ailter2onfig filter2onfigM
public void doAilter (ServletHe*uest re*uest ServletHesponse response Ailter2hain chain)
L
try
L
chain.doAilter (re*uest response)M II for =ilter Chain
N catch ($&-xception io) L
System.out.println (K$&-xception raised in SimpleAilterK)M
N
N
public Ailter2onfig getAilter2onfig()
L
return this.filter2onfigM
N
public void setAilter2onfig (Ailter2onfig filter2onfig)
L
this.filter2onfig Q filter2onfigM
N
N
Filter and the RequestDispatcher
version 9.U of the Java Servlet specification is the ability to configure filters to be invo'ed under re*uest dispatcher
forward() and include() calls. Cy using the new "dispatcher#$02@R3- % A&H,AH3"%dispatcher# element in the
deployment descriptor
Q) "re (ervlets mltithread?
") 8es the servlet container allocates a thread for each new re*uest for a single servlet. -ach thread of your servlet
runs as if a single user were accessing using it alone but u can use static variable to store and present information that
is common to all threads li'e a hit counter for instance.
Q) What happens to (ystem*ot % (ystem*err otpt in a (ervlet?
A) System.out goes to Jclient sideJ and is seen in browser while System.err goes to Jserver sideJ and is visible in error
logs and%or on console.
Q) (ession +rac)in$
Session trac'ing is the capability of the server to maintain the single client se*uential list.
Q) (ervlet chainin$
$s a techni*ue in which two are more servlets cooperating in servicing a single client se*uential re*uest where
one servlet output is piped to the next servlet output. The are 9 ways (i) Servlet Aliasing (ii) 1ttpHe*uest
Servlet Aliasing allow you to setup a single alias name for a comma delimited list of servlets. To ma'e a servlet chain
open your browser and give the alias name in RH@.
1ttpHe*uest construct a RH@ string and append a comma delimited list of servlets to the end.
Q) <ttp+nnellin$
$s a method used to reading and writing seriali!es ob(ects using a http connection. 8ou are creating a sub
protocol inside http protocol that is tunneling inside another protocol.
Q) #iff C8I % (ervlet
Servlet is thread based but 24$ is process based.
24$ allow separate process for every client re*uest 24$ is platform dependent and servlet is platform independent.
Q) #iff 8E+ % PO(+
4-T T P&ST are used to process re*uest and response of a client.
4-T method is the part of RH@ we send less amount of data through 4-T. The amount of information limited is 9U?/
9BB characters (or >'b in length).
Rsing P&ST we can send large amount of data through hidden fields.
4et is to get the posted html data P&ST is to post the html data.
Q) #iff <ttp % 8eneric (ervlet
1ttpServlet class extends 4eneric servlet so 4eneric servlet is parent and 1ttpServlet is child.
4eneric is from (avax.servlet pac'age 1ttpServlet is from (avax.servlet.1ttp pac'age.
1ttp implements all 1ttp protocols 4eneric servlet will implements all networ'ing protocol
1ttp is stateless protocol which mean each re*uest is independent of previous one $n generic we cannot maintain
the state of next page only main state of current page.
A protocol is said to be stateless if it has n memory of prior connection.
1ttp servlet extra functionality is capable of retrieving 1ttp header information.
1ttp servlet can override do4et() do3elete() do4et() doPost() doTrace() generic servlet will override Service()
method only.
Q) Can I catch servlet e9ception and $ive my own error messa$e? !or) cstom error pa$es?
A) 8es you can catch servlet errors and give custom error pages for them but if there are exceptional conditions you
can anticipate it would be better for your application to address these directly and try to avoid them in the first place. $f a
servlet relies upon system or networ' resources that may not be available for unexpected reasons you can use a
He*uest3ispatcher to forward the re*uest to an error page.
He*uest3ispatcher dispatcher Q nullM
re*uest.getHe*uest3ispatcher(%err%SY@.(sp)M
try L
%% SY@ operation
N
catch (SY@-xception se) L
dispatcher.forward(re*uest response)M
N
,eb.xml
"error/page#
"error/code#
1TTP error code (U?U)
"error/code#
"exception/type#
java.lang.RuntimeException
"%exception/type#
"location#
/err/RuntimeException.jsp
"%location#
"%error/page#
Q) <ow many ways we can instantiate a class?
") 2lass.for0ame().new$nstance() and new 'eyword
Q) Client pll % (erver psh?
Client pll
2lient pull is similar to redirection with one ma(or difference. the browser actually displays the content from the
first page and waits some specified amount of time before retrieving and displaying the content from the next page. $tJs
called client pull because the client is responsible for pulling the content from the next page.
2lient pull information is sent to the client using the Hefresh 1TTP header. This headerJs value specifies the number of
seconds to display the page before pulling the next one and it optionally includes a RH@ string that specifies the RH@
from which to pull. $f no RH@ is given the same RH@ is used. 1ereJs a call to set1eader() that tells the client to reload
this same servlet after showing its current content for three seconds. set1eader(KHefreshK K<K)M
And hereJs a call that tells the client to display 0etscapeJs home page after the three seconds.
set1eader(KHefreshK K<M RH@Qhttp.%%home.netscape.comK)M
(erver psh
Server push because the server sends or pushes a se*uence of response pages to the client. ,ith server
push the soc'et connection between the client and the server remains open until the last page has been sent.
<META HTTP-EQUIV="Refresh" CONTENT="5;URL=/servlet/st!"#$tes/"%
Q) <ow can a servlet refresh atomatically if some new data has entered the database?
") 8ou can use client side refresh are server push
Q) <ow can i pload =ile sin$ a (ervlet?
"A&H) -02T8P-QKmltipartIform.dataK methodQpost actionQK%utils%AileRploadServletK#
"$0PRT T8P-QKfileK 0A)-QKcurrentfilenameK#
"$0PRT T8P-QKsubmitK 7A@R-QKuploadK#
"%A&H)#
Q) (ession +rac)in$ techniFes

!i) 71D 1ewritin$
!ii) <idden form =ield
!iii) Persistence Coo)ies
!iv) (ession +rac)in$ "PI
!v) 7ser "thori6ation
71D 1ewritin$
RH@ rewriting is a techni*ue in which the re*uested RH@ is modified with the session id.
RH@ rewriting is another way to support anonymous session trac'ing. ,ith RH@ rewriting every local 71D the user
might clic' on is dynamically modified or rewritten to include extra information.
http.%%server.port%servlet%Hewritten+sessionidQ>9< added parameter
<idden form =ield
1idden form fields are 1T)@ input type that are not displayed when read by the browser. They are sent bac' to
the server when the form that contains them is submitted. 8ou include hidden form fields with 1T)@ li'e this.
"A&H) A2T$&0QK%servlet%)ovieAinderK )-T1&3QKP&STK#
"$0PRT T8P-Qhidden 0A)-QK!ipK 7A@R-QKVU?U?K#
"$0PRT T8P-Qhidden 0A)-QKlevelK 7A@R-QKexpertK#
"%A&H)#
$n a sense hidden form fields define constant variables for a form. To a servlet receiving a submitted form there is no
difference between a hidden field and a visible field.
Persistence Coo)ie
A coo.ie is a bit of information sent by a web server to a browser that can later be read bac' from that browser.
,hen a browser receives a coo'ie it saves the coo'ie and thereafter sends the coo'ie bac' to the server each time it
accesses a page on that server sub(ect to certain rules. Cecause a coo'ieJs value can uni*uely identify a client coo'ies
are often used for session trac'ing. Cecause coo'ies are sent using 1TTP headers they should be added to the
response before you send any content. Crowsers are only re*uired to accept 9? coo'ies per site <?? total per user and
they can limit each coo'ieJs si!e to U?V; bytes.
Sending cookies from a servlet
2oo'ie coo'ie Q new 2oo'ie (K$3K K>9<K)M
res.add2oo'ie (coo'ie)M
A servlet retrieves coo'ies by calling the get2oo'ies () method of 1ttpServlet/ He*uest.
public 2oo'ieOP 1ttpServletHe*uest.get2oo'ies()
This method returns an array of 2oo'ie ob(ects that contains all the coo'ies sent by the browser as part of the re*uest
or null if no coo'ies were sent. The code to fetch coo'ies loo's li'e this.
,eading bro-ser cookies from a Servlet
2oo'ie OP coo'ies Q re*. get2oo'ies()M
if (coo'ies WQ null) L
for (int i Q ?M i " coo'ies.lengthM iSS) L
String name Q coo'ies OiP. get0ame ()M
String value Q coo'ies OiP. get7alue()M
N
N
%eleting the Cookies
"Z
2oo'ie 'ill)y2oo'ie Q new 2oo'ie(Kmycoo'ieK null)M
'ill)y2oo'ie.set'a9"$e(?)M
'ill)y2oo'ie.setPath(K%K)M
response.add2oo'ie('ill)y2oo'ie)M
Z#
8ou can set the maximum age of a cookie with the cookie.setMaxAge(int seconds) method
Nero means to delete the coo'ie
+ vale is the maximum number of seconds the coo'ie will live before it expires
. vale means the coo'ie will not be stored beyond this browser session (deleted on browser close)
(ession +rac)in$ "PI
$n Java the (avax.servlet.http.1ttpSession AP$ handles many of the details of session trac'ing. $t allows a
session ob(ect to be created for each user session then allows for values to be stored and retrieved for each session. A
session ob(ect is created through the 3ttp(ervlet4e5uest using the getSession() method.
1ttpSession session Q re*uest.getSession(true)M
This will return the session for this user or create one if one does not already exist. 7alues can be stored for a user
session using the 3ttp(ession method put7alue().
session.put7alue(Kvalue0ameK value&b(ect)M
Session ob(ects can be retrieved using get7alue(String name) while a array of all value names can be retrieved using
get7alue0ames(). 7alues can also be removed using remove7alue(String value0ame)
7ser "thori6ation
Servers can be set up to restrict access to 1T)@ pages (and servlets). The user is re*uired to enter a user
name and password. &nce they are verified the client re/sends the authorisation with re*uests for documents to that
site in the http header.
Servlets can use the username authorisation sent with re*uest to 'eep trac' of user data. Aor example a hashtable can
be set up to contain all the data for a particular user. ,hen a user ma'es another re*uest the user name can be used to
add new items to their cart using the hashtable.
Q) 1etrievin$ Fery parameters names?
-numeration params Q re*uest.getParameter0ames()M
String param0ame Q nullM
StringOP param7alues Q nullM
while (params.has)ore-lements()) L
param0ame Q (String) params.next-lement()M
param7alues Q re*uest.getParameter7alues(param0ame)M
System.out.println(KFnParameter name is K S param0ame)M
for (int i Q ?M i " param7alues.lengthM iSS) L
System.out.println(K value K S i S K is K S
param7aluesOiP.toString())M
N
N
Q) (ession
Session is a persistence networ' connection between client and server that facilitate the exchange of
information between client and server. The container generates a session $3 when you create a session the server
saves the session $3 on the clients machine as a coo'ie. A session ob(ect created for each user persists on the server
side either until user closes the browser or user remains idle for the session expiration time.
As such there is no limit on the amount of information that can be saved in a Session &b(ect. &nly the HA)
available on the server machine is the limitation. The only limit is the Session $3 length ($dentifier) which should not
exceed more than UI. $f the data to be store is very huge then itJs preferred to save it to a temporary file onto hard dis'
rather than saving it in session. $nternally if the amount of data being saved in Session exceeds the predefined limit
most of the servers write it to a temporary cache on 1ard dis'.
%% $f 5+re6 means creating a session if session is not there
%% if 5=alse6 means session is not created should one does not exist
1ttpSession session Q re*.getSession(true)M
session.put7alue (K)y$dentifier>K count>)M %% Storing 7alue into session &b(ect
session.put7alue (K)y$dentifier9K count9)M
session.get7alue()y$dentifier>)M %% Prints value of 2ount
session.remove7alue()y$dentifier>)M %% Hemoving 7aluefrom Session &b(ect
Invalidating a Session
There are ; different ways to invalidate the session.
> 1ttpsession.set)ax$nactive$ntervel(int sec)
9 Session will automatically expire after a certain time of inactivity
< Rser closes browser window notice that the session will time out rather than directly triggering session invalidate.
U calling invalidate()
B if server cashes
; put "session/timeout# in web.xml
Q) Coo)ie advanta$es % #isadvanta$es
"dvanta$es Persistence offer efficient way to implement session trac'ing for each client re*uest a coo'ie can be
automatically provide a clients session id.
#isadvanta$e The biggest problem with coo'ies is that browser do not always accept coo'ies. Some times browser
does not accept coo'ies. Crowser only re*uires accepting 9? coo'ies per page and they can limit the coo'ie si!e to
U?V; bytes. $t cannot wor' if the security level set too high in browser. 2oo'ies are stored in a plain text format so every
one can view and modify them. ,e can put maximum <?? coo'ies for entire application.
Q) "dvanta$es of (essions over Coo)ies % 71D1ewritin$?
Sessions are more secure and fast because they are stored at server side. Cut sessions has to be used combindly
with coo'ies (or) RH@Hewriting for maintaining client id that is session id at client side.
2oo'ies are store at client side so some clients may disable coo'ies so we may not sure that the coo'ies which we
are maintaining may wor' or not if coo'ies are disable also we can maintain sessions using RH@Hewriting.
$n RH@Hewriting we cannot maintain large data because it leads to networ' traffic and access may be become slow.
,here in sessions will not maintain the data which we have to maintain instead we will maintain only the session id.
Q) If the coo)ies at client side are disabled then session donGt wor)5 in this case how can we proceed?
") >. (from servlet) write the next page with a hidden field containing a uni*ue $3 that serves as Ksession $3K. So next
time when the user clic's submit you can retrieve the hidden field.
9. $f you use applet you may avoid Kview sourceK (so that people canJt see the hidden field). 8our applet reads bac'
an $3 from the servlet and use that from then on to ma'e further re*uests
Q) <ow to confirm that serGs browser accepted the Coo)ie?
") ThereJs no direct AP$ to directly verify that userJs browser accepted the coo'ie. Cut the *uic' alternative would be
after sending the re*uired data to the users browser redirect the response to a different Servlet which would try to read
bac' the coo'ie. $f this Servlet is able to read bac' the coo'ie then it was successfully saved else user had disabled
the option to accept coo'ies.
Q) #iff between 'ltiple Instances of 0rowser and 'ltiple Windows? <ow does this affect (essions?
") Arom the current Crowser window if we open a new ,indow then it referred to as )ultiple ,indows. Sessions
properties are maintained across all these windows even though they are operating in multiple windows.
$nstead if we open a new Crowser by either double clic'ing on the Crowser Shortcut then we are creating a new
$nstance of the Crowser. This is referred to as )ultiple $nstances of Crowser. 1ere each Crowser window is considered
as different client. So Sessions are not maintained across these windows.
Q) encode71D % encode1edirect71D
These are methods of 1ttpHesponse ob(ect 5encodeRH@6 is for normal lin's inside your 1T)@ pages
5encodeHedirectRH@6 is for a lin' your passing to response.sendHedirect().
Q) (in$le+hread model
SingleThread)odel is a tag interface with no methods. $n this model no two threads will execute concurrently
the service method of the servlet to accomplish this each thread uses a free servlet instance from the servlet pool. So
any servlet implementing this can be considered thread safe and it is not re*uired synchroni!e access to its variables.
!or)
$f a servlet implements this interface the server ensures that each instance of the servlet handles only one
service re*uest at a time. Servers implement this functionality by maintaining a pool of servlet instances and dispatching
incoming re*uests to free servlets within the pool. SingleThread)odel provides easy thread safety but at the cost of
increased resource re*uirements as more servlet instances are loaded at any given time.
public interface SingleThread)odel L
N
Q) 1eFest <eaders
7ser.a$ent> . 4ives the information about client software browser name version and information about the machine on
which it is running.
re*uest.get1eader(5user/agent6)M
Q) Why do yo need both 8E+ % PO(+ methods in servlets?
") A single servlet can be called from different 1T)@ pages so different method calls can be possible.
Q) (ervlet otpt . to . another (ervlet+ Inter.servlet commnication?
A) As the name says it it is communication between servlets. Servlets tal'ing to each other. OThere are many ways to
communicate between servlets including
He*uest 3ispatching
1TTP Hedirect
Servlet 2haining

(ervlet6
Servlet2ontext sc Q getServlet2ontext()M
He*uest3ispatcher rd Q sc.getHe*uest3ispatcher (5%..%srevlet96) M
rd.forward(re* res)M

(ervlet7
Public void service(servletHe*uest re* servletHesponse res)
L
Servlet2ontext sc Q getServlet2ontext()M
He*uest3ispatcher rd Q sc.getHe*uest3ispatcher (5%..%srevlet>6) M
rd.include(re* res)M
N
Casically interServlet communication is acheived through servlet chaining. ,hich is a process in which you pass the
output of one servlet as the input to other. These servlets should be running in the same server.
E9>. Servlet2ontext.getHe*uest3ispatcher(1ttpHe*uest 1ttpHesponse).forward(K0extServletK) M
8ou can pass in the current re*uest and response ob(ect from the latest form submission to the next servlet%JSP. 8ou
can modify these ob(ects and pass them so that the next servlet%JSP can use the results of this servlet.
There are some Servlet engine specific configurations for servlet chaining.
Servlets can also call public functions of other servlets running in the same server. This can be done by obtaining a
handle to the desired servlet through the Servlet2ontext &b(ect by passing it the servlet name ( this ob(ect can return
any servlets running in the server). And then calling the function on the returned Servlet ob(ect.
E9>. TestServlet testQ (TestServlet)getServlet2onfig().getServlet2ontext().getServlet(K&therServletK)M
otherServlet3etailsQ Test.getServlet3etails()M
8ou must be careful when you call another servletJs methods. $f the servlet that you want to call implements the
SingleThread)odel interface your call could conflict with the servletJs single threaded nature. (The server cannot
intervene and ma'e sure your call happens when the servlet is not interacting with another client.) $n this case your
servlet should ma'e an 1TTP re*uest to the other servlet instead of direct calls.
Servlets could also invo'e other servlets programmatically by sending an 1TTP re*uest. This could be done by opening
a RH@ connection to the desired Servlet.
Q) (ervlet O to. J(PI(ervlet commnicate? !or) <ow (ervlet invo)e a J(P pa$e?
public void doPost(1ttpServletHe*uest re*
1ttpServletHesponse res)L
TryL
govi.AormCean f Q new govi.formCean()M
f.set0ame(re*.getParameter(5name6))M
f.setAdress(re*.getParameter(5addr6))M
f.setPersonali!ation$nfo(info)M
re*.setAttribute(5fCean6f)M
getServlet2onfig().getServlet2ontext().getHe*uest3ispatcher(5%(sp%Cean>.(sp6).forward(re* res)M
N catch(-xception ex)M
N
N
The (sp page Cean>.(sp can then process fCean
"(sp.useCean idQ6fCean6 classQ6govi.formCean6 scopeQ6re*uest6 %#
"(sp.getProprety nameQ6fCean6 propertyQ6name6 %#
"(sp.getProprety nameQ6fCean6 propertyQ6addr6 %#
............................................................ !Or) .................................................................
8ou can invo'e a JSP page from a servlet through functionality of the standard (avax.servlet.He*uest3ispatcher
interface. 2omplete the following steps in your code to use this mechanism.
>) 4et a servlet context instance from the servlet instance.
Servlet2ontext sc Q this.getServlet2ontext()M
9) 4et a re*uest dispatcher from the servlet context instance specifying the page/relative or application/relative path of
the target JSP page as input to the getHe*uest3ispatcher() method.
He*uest3ispatcher rd Q sc.getHe*uest3ispatcher(K%(sp%mypage.(spK)M
Prior to or during this step you can optionally ma'e data available to the JSP page through attributes of the 1TTP
re*uest ob(ect. See KPassing 3ata Cetween a JSP Page and a ServletK below for information.
<) $nvo'e the include() or forward() method of the re*uest dispatcher specifying the 1TTP re*uest and response
ob(ects as arguments.
rd.include(re*uest response)M % rd.forward(re*uest response)M
The functionality of these methods is similar to that of (sp.include and (sp.forward actions. The include() method only
temporarily transfers controlM execution returns to the invo'ing servlet afterward.
0ote that the forward() method clears the output buffer.
Q) c onte9t*$et1eFest#ispatcher!)
reFest*$et1eFest#ispatcher!)
conte9t*$et-amed#ispatcher!)
>) Servlet2ontext.getHe*uest3ispatcher( % ) PC 8ou must use Absolute paths it can extend outside current
servlet context.
9) ServletHe*uest.getHe*uest3ispatcher(Helative Path) PC The path may be Helative but cannot extend outside
current servlet context the 71D in the address bar doesnQt chan$e. The client looses path information when it receives
a forwarded re*uest.
<) ServletHe*uest.get0amed3ispatcher(String name) PC This name is the name of the servlet for which a dispatcher
is re*uested and is in the web.xml file
-x ./
public class ServletToServlet extends 1ttpServlet
L
public void do4et (1ttpServletHe*uest re* 1ttpServletHesponse res) throws Servlet-xception $&-xception
L
try L
getServlet2onfig()
.getServlet2ontext().getHe*uest3ispatcher(K%1ello,orld-xampleK).forward(re*uest response)M
N catch (-xception ex) L
ex.printStac'Trace ()M
N
N
N
He*uest3ispatcher dispatcher Q getServlet2ontext().getHe*uest3ispatcher(path)M
if (dispatcher QQ null)
L
out.println(path S K not availableK)M
returnM
N else
L
dispatcher.include(re*uest response)M
N
Q) #ifferent cases for sin$ send1edirect!) vs* $et1eFest#ispatcher!) % $et-amed#ispatcher?
,hen you want to preserve the current re*uest%response ob(ects and transfer them to another resource ,$T1$0 the
context you must use getHe*uest3ispatcher (or) get0amed3ispatcher.
$f you want to dispatch to resources &RTS$3- the context then you must use sendHedirect. $n this case you wonJt
be sending the original re*uest%response ob(ects but you will be sending a header as'ing to the browser to issue a
re*uest to the new RH@.
Q) <ow can I pass data from a servlet rnnin$ in one conte9t !webapp) to a servlet rnnin$ in another conte9t?
") 8ou can bind this information to a context that is accessible to all servlet contexts such as the application serverJs
context. This way you can 'eep the data you want to share in memory.
Q) <ow can I share data between two different web applications?
") 3ifferent servlets may share data within one application via ServletConte't. $f you have a compelling to put the
servlets in different applications.
Q) <ow do servlets handle mltiple simltaneos reFests?
") The server has multiple threads that are available to handle re*uests. ,hen a re*uest comes in it is assigned to a
thread which calls a service method (for example. do4et() doPost( ) and service( ) ) of the servlet. Aor this reason a
single servlet ob(ect can have its service methods called by many threads at once.
Q) <ow do i $et the name of the crrently e9ectin$ script?
") re*.getHe*uestRH$() I re*.getServletPath(). The former returns the path to the script including any extra path
information following the name of the servletM the latter strips the extra path info.
71D http.%%www.(avasoft.com%servlets%1elloServlet%(data%userinfo+pagetypeQs<TpagenumQU
8et1eFest71I servlets%1elloServlet%(data%userinfo
8et(ervletPath servlets%1elloServlet%
8etPathInfo %(data%userinfo
8etQery(trin$ pagetypeQs<TpagenumQU
Q) <ow can i stress test my (ervlets?
") following products to stress test your Servlets.
ServletIiller -/@oad ,eb Application Stress Tool J)eter from Apache
Q) Connection pool class
public class 2onnectionPool L
private 1ashtable connectionsM
private int incrementM
private String dbRH@ user passwordM

public 2onnectionPool(String dbRH@ String user String password String driver2lass0ame
int initial2onnections int increment) throws SY@-xception 2lass0otAound-xception L

2lass.for0ame(driver2lass0ame)M
this.dbRH@ Q dbRH@M
this.user Q userM
this.password Q passwordM
this.increment Q incrementM
connections Q new 1ashtable()M

%% Put our pool of 2onnections in the 1ashtable
%% The AA@S- value indicates theyJre unused
for(int i Q ?M i " initial2onnectionsM iSS) L
connections.put(3river)anager.get2onnection(dbRH@ user password) Coolean.AA@S-)M
N
N
public 2onnection get2onnection() throws SY@-xception L
2onnection con Q nullM
-numeration cons Q connections.'eys()M
synchroni!ed (connnections) L
while(cons.has)ore-lements()) L
con Q (2onnection)cons.next-lement()M
Coolean b Q (Coolean)connections.get(con)M
if (b QQ Coolean.AA@S-) L
%% So we found an unused connection. Test its integrity with a *uic' setAuto2ommit(true) call.
%% Aor production use more testing should be performed such as executing a simple *uery.
try L
con.setAuto2ommit(true)M
N
catch(SY@-xception e) L
%% Problem with the connection replace it.
con Q 3river)anager.get2onnection(dbRH@ user password)M
N
%% Rpdate the 1ashtable to show this oneJs ta'en
connections.put(con Coolean.THR-)M
return conM
N
N
N

%% $f we get here there were no free connections.
%% ,eJve got to ma'e more.
for(int i Q ?M i " incrementM iSS) L
connections.put(3river)anager.get2onnection(dbRH@ user password)
Coolean.AA@S-)M
N

%% Hecurse to get one of the new connections.
return get2onnection()M
N
public void return2onnection(2onnection returned) L
2onnection conM
-numeration cons Q connections.'eys()M
while (cons.has)ore-lements()) L
con Q (2onnection)cons.next-lement()M
if (con QQ returned) L
connections.put(con Coolean.AA@S-)M
brea'M
N
N
N
N
J(P Qestions
#irectives
Page Page 3irective "Za Page languageQK(avaK extendsQKclass0ameK
importQKclass0ameK sessionQKtre]falseK bufferQK^ICK
autoAlushQKtre%falseK isThreadSafeQKtre%falseK infoQKtextK
errorPageQK(spRrlK is-rrorPageQKtrue%falseK
contentTypeQKmimeType6 Z#
J'D synta9> .
Page directive defines information
that will be globally available for that
page
"Jsp. directive.page importQ6 6 %#
$nclude
3irective
"Za include fileQKrelative RH@K Z#
J'D synta9> .
"Jsp. directive.include fileQ6 6 %#
"Jsp. directive.page fileQ6 6 %#
$nclude JSP are Servlet at compile
time meaning that only once parsed
by the compiler it will act as a 526
KbincludeK pulling in the text of the
included file and compiling it as if it
were part of the including file. ,e can
also include :(tatic; files using this
directive.
Taglib 3irective "Za taglib uriQKuri8o8ag'ibraryK prefixQKpre"ix(tringK Z#
J'D synta9> .
"Jsp. root xmlns.prefix>Q6http.%%..6 versionQ6>.96 %#
"%Jsp. root#
Taglib directive enables you to create
your own custom tags.
"ctions
./sp0 use1ean2 "Jsp. useCean idQKbeanInstance-ameK scopeQKpa$e]
re*uest]session]application6 classQKK%
typeQKK bean 0ameQK K"%(sp. useCean#
RseCean tag is used to associate a
(ava bean with (sp.
./sp0 set3roperty2 "Jsp. setProperty nameQKbeanInstance-ame6
propertyQKXK ]Kproperty-ame6 paramQKparam-ameK
valueQKLstring ] "ZQ expression Z#NK %#
Sets a property value or values in a
bean.
./sp0 get3roperty2 "Jsp. getProperty nameQKbeanInstance-ameK
propertyQKproperty-ameK %#
4ets the value of a bean property so
that you can display it in a result
page.
./sp0 param2 "Jsp. param nameQKbeanInstance-ameK valueQK
parameter0alue K %#
$t is used to provide other tags with
additional information in the form of
name value pairs. This is used to
con(unction with jsp1include,
jsp1"or9ard, jsp1plugin!
./sp0 include2 "Jsp. include pageQKrelative+4' K flushQKtrueK #
"Jsp. param nameQKusernameK valueQK(smithK %#
"%(sp. include#
Jsp $nclude includes the JSP are
Servlet at re*uest time it is not
parsed by the compiler and it
$ncludes a static file or sends a
re*uest to a dynamic file.
BJsp> forwardC "Jsp. forward pageQKLrelative4,L]:;<expression ;>NK #
"(sp. param nameQKparam-ameK valueQKparam0alueK%#
"%(sp. forward#
,hen ever the client re*uest will
come it will ta'e the re*uest and
process the re*uest and the re*uest
to be forward to another page and it
will also forward the http parameters
of the previous page to the destination
page. $t will wor' at server side.
./sp0 plugin2 "Jsp. plugin typeQKbean%appletK codeQKclass&ile-ameK
codebaseQKclass&ile=irectory-ameK
nameQKinstance-ameK archiveQK6 alignQKK heightQK K
widthQK K hspaceQK K vspaceQK "%(sp. plugin#
This action is used to generate client
browser specific html tags that
ensures the (ava plug in software is
available followed by execution of
applet or (ava bean component
specified in tag.
Implicit Ob&ects
5b+ects $ype ! purpose Scope Sum useful methods
1eFest Subclass of javax!servlet!http!(ervlet4e5uest
2 Hefers to the current re*uest passed to the
c(spService() method
He*uest
/ &b(ects accessible from
pages processing the re*uest
where they were created.
getAttribute
getParameter
getParameter0ames
getParameter7alues
setAttribute
1esponse Subclass of javax!servlet!http!(ervlet4esponse
2 Hefers to the response sent to the client. $t is
also passed to the c(spService() method.
Page 0ot typically used by
JSP page authors
(ession javax!servlet!http!3ttp(ession
2 JSP >.9 specification states that if the session
directive is set to false then using the session
'eyword results in a fatal translation time error.
Session
/ &b(ects accessible from
pages belonging to the same
session as the one in which
they were created.
getAttribute get$d
setAttribute.
"pplication +ava'#servlet#ServletConte't
/ Rse it to find information about the servlet
engine and the servlet environment.
Application
/ &b(ects accessible from
pages belonging to the same
application.
getAttribute
get)imeType
getHealPath
setAttribute
Ot javax!servlet!jsp!>sp?riter
/ Hefers to the output stream of the JSP page.
Page clear clearCuffer flush
getCufferSi!e
getHemaining
Confi$ javax!servlet!(ervletCon"ig
/ The initiali!ation parameters given in the
deployment descriptor can be retrieved from this
ob(ect.
Page get$nitParameter
get$nitParameter0ames
Pa$e java!lang!Object!
2 Hefers to the current instance of the servlet
generated from the JSP page.
Page
/ &b(ects accessible only
within (sp pages where it was
created.
-ot typically used by
>(, page authors
pa$eConte9t javax!servlet!jsp!,ageContext!
/ Provides certain convenience methods and
stores references to the implicit ob(ects.
Page findAttribute
getAttribute
getAttributesScope
getAttribute0ames$nSc
ope setAttribute.
E9ception java!lang!8hro9able!
2 Available for pages that set the page directive
attribute is-rrorPage to true. $t can be used for
exception handling.
Page get)essage
get@ocali!ed)essage
printStac'Trace
toString

(criptlet "Z Javaccode Z#
J'D synta9> .
"Jsp. scriptlet#
3ate today Q new 3ate()M
"%(sp. scriptlet#
A scriptlet can contain variable (or) method declarations (or)
expressions. Scriptlets are executed at re*uest time when
the JSP engine processes the client re*uest. $f the scriptlet
produces output the output is stored in the out ob(ect from
which you can display it.
#eclaration E9> "ZW int a b cM Z#
"ZW int accountnumberQ9<U;^M Z#
"ZW private void processAmount () L ... N
Z#
J'D synta9> .
"(sp. declaration#
int counterQ?M
"%(sp. 3eclaration#
A declaration declares one or more variables (or) methods
for use later in the JSP source file. This is used for :8lobal
declaration;*
E9pressions E9> "ZQ (new
(ava.util.3ate()).to@ocaleString() Z#
J'D synta9> .
"(sp. expression#
%% ///////
"%(sp. expression#
An expression tag contains a scripting language expression
that is evaluated converted to a String and inserted where
the expression appears in the JSP file.
Comments <tml comment 2reates a comment that
is sent to the client in the viewable page
source.
-x. "W // "ZQ expression Z# //#
<idden Comment 3ocuments the JSP
file but is not sent to the client.
-x. "Z// comment //Z#
2omments are removed from the viewable source of your
1T)@ files by using only JSP comment tags. 1T)@
comments remain visible when the user selects view source
in the browser.
Q) #iff E9plicit Ob&ects % Implicit Ob&ects
&'plicit -xplicit ob(ects are declared and created within the code of your JSP page accessible to that page and other
pages according to the scope setting you choose.
-xplicit ob(ects are typically JavaCean instances declared and created in (sp.useCean action statements. "(sp.useCean
idQKpageCeanK classQKmybeans.0ameCeanK scopeQKpageK %#
Implicit $mplicit ob(ects are created by the underlying JSP mechanism and accessible to Java scriptlets (or)
expressions in JSP pages according to the inherent scope setting of the particular ob(ect type.
Q) '/C
'odel> . model is a (ava bean%entity bean that represent the data being transmitted are received
Controller> . 2ontroller is a servlet that performs necessary manipulations to the model.
/iew> . is a screen representation of the model.
)a(or benefits of using the )72 design pattern is separate the view T model this ma'e it is possible to create are
change views with out having to change the model.
>) The browser ma'es a re*uest to the controller servlet 9) Servlet performs necessary actions to the (ava bean
model and forward the result to the (sp view. <) The (sp formats the model for display and send the html results bac' top
the web browser.
Q) Web"pplication scopes?
") He*uest Session Application.
He*uest ./ @ife time is until the response is return to the user
Session ./ Rntil the session timeout (or) session id invalidate.
Application ./ @ife of container (or) explicitly 'illed
Q) Dife.cycle of J(P
Pa$e translation
Jsp compilation
Doad class
Create Instance
&spInit! )5 R&spservice! )5 &sp#estroy! )
&spInit! ) container calls the (sp$nit() to initiali!e to servlet instance. $t is called before any other method and is
called only once for a servlet instance.
R&spservice! ) container calls c(spservice() for each re*uest passing it the re*uest and the response ob(ects.
&sp#estroy! ) container calls this when it decides ta'e the instance out of service. $t is the last method called n the
servlet instance.
3estroy is not called if the container crashes!
(sp$nit() T (sp3estroy() called only once so we cannot override these methods.
Q) 1eFest#ispatcher*forward!reF5 res)
1eFest#ispatcher*inclde!reF5 res)
Pa$eConte9t*forward!)
res*send1edirect!rl)
B&sp>forwardC

1eFest#ispatcher*forward!reF5 res) in forward re* res would be passed to the destination RH@ and the
control will return bac' to the same method it will execute at 5server side6.

res*send1edirect!rl) when ever the client re*uest will come (ust it will ta'e the re*uest and the re*uest to be
forwarded to another page. $t cannot forward the http parameters of the previous page. This will wor' at 5client side6. $f
page>.(sp redirects to page9.(sp the browserJs address bar be updated to show page9.(sp.
Pa$eConte9t*forward!) and He*uest3ispatcher.forward() are effectively the same. Page2ontext.forward is a
helper method that calls the He*uest3ispatcher method.
The difference between the two is that sendHedirect always sends a header bac' to the client%browser. this header then
contains the resource(page%servlet) which you wanted to be redirected. the browser uses this header to ma'e another
fresh re*uest. thus sendHedirect has a overhead as to the extra remort trip being incurred. itJs li'e any other 1ttp
re*uest being generated by your browser. the advantage is that you can point to any resource(whether on the same
domain or some other domain). for eg if sendHedirect was called at www.mydomain.com then it can also be used to
redirect a call to a resource on www.theserverside.com.
$n the case of forward() call the above is not true. resources from the server where the fwd. call was made can only be
re*uested for. Cut the ma(or diff between the two is that forward (ust routes the re*uest to the new resources which you
specify in your forward call. that means this route is made by the servlet engine at the server level only. no headers are
sent to the browser which ma'es this very efficient. also the re*uest and response ob(ects remain the same both from
where the forward call was made and the resource which was called.
1eFest#ispatcher*inclde!reF5 res) He*uest3ispatcher.include() and "(sp.include# both include content.
The included page is inserted into the current page or output stream at the indicated point. $t will execute at 5server
side6.
BJsp> forwardC Aorwards a client re*uest to an 1T)@ file%JSP file%servlet for processing. ,hen ever the client
re*uest will come it will ta'e the re*uest and process the re*uest and the re*uest to be forward to another page it will
also forward the http parameters of the previous page to the destination page. $t will execute at 5server side6 so the
browser unaware of the changes. $f page>.(sp redirects to page9.(sp the browser address bar will still show page>.(sp.
Aorward operations are faster because all processing is done at server side. res.sendHedirect() operations updates the
browser history.
E9 .. of 1eFest#ispatcher*forward!reF5 res)
public class Coo'StoreServlet extends 1ttpServlet L
public void do4et(1ttpServletHe*uest re* 1ttpServletHesponse res) throws Servlet-xception $&-xception L
%% 4et the dispatcherM it gets the main page to the user
He*uest3ispatcher dispatcher Q config.getServlet2ontext().getHe*uest3ispatcher(K%boo'store.htmlK)M
if (dispatcher QQ null) L
%% 0o dispatcher means the resource (boo'store.html in this case) cannot be found
res.send-rror(response.S2c0&c2&0T-0T)M
N else L
%% Send the user the boo'storeJs opening page
dispatcher.forward(re*uest response)M
N
Q) #iff res*send1edirect! ) % reF*forward! )
sendHedirect() sends a redirect response bac' to the clientJs browser. The browser will normally interpret this
response by initiating a new re*uest to the redirect RH@ given in the response.
forward() does not involve the clientJs browser. $t (ust ta'es browserJs current re*uest and hands it off to
another servlet%(sp to handle. The client doesnJt 'now that theyJre re*uest is being handled by a different servlet%(sp than
they originally called.
Aor ex if you want to hide the fact that youJre handling the browser re*uest with multiple servlets%(sp and all of
the servlets%(sp are in the same web application use forward() or include(). $f you want the browser to initiate a new
re*uest to a different servlet%(sp or if the servlet%(sp you want to forward to is not in the same web application use
sendHedirect ().
Q) #iff BST inclde fileEUfileU SC % B&sp>inclde pa$eE;abc*&sp; SC
"Zainclude fileQKabc.(spKZ# directive acts li'e 2 KbincludeK pulling in the text of the included file and
compiling it as if it were part of the including file. The included file can be any type (including 1T)@ or text). (&r)
includes a (sp%servlet at compile time meaning only once parsed by the compiler.
"(sp.include pageQKabc.(spK# include a (sp%servlet at re*uest time it is not parsed by the compiler.
Q) #iff Jsp % (ervlet
$nternally when (sp is executed by the server it get converted into the servlet so the way (sp T servlet wor' is almost
similar.
$n (sp we can easily separate the P.@ with C.@ but in servlet both are combined.
&ne servlet ob(ect is communicate with many number of ob(ects but (sp it is not possible.
Q) Can J(P be mlti.threaded? <ow can I implement a thread.safe J(P pa$e?
") Cy default the service() method of all the JSP execute in a multithreaded fashion. 8ou can ma'e a page 5thread/safe6
and have it serve client re*uests in a single/threaded fashion by setting the page tagGs is Thread Safe attribute to false.
"Za page is ThreadSafeQ6false6 Z#
Q) <ow does J(P handle rntime e9ceptions?
") 8ou can use the errorPage attribute of the page directive to have uncaught run-time e'ceptions automatically
forwarded to an error processing page. Aor example.
"Za page errorPageQFKerror.(spFK Z#
redirects the browser to the JSP page error.(sp if an uncaught exception is encountered during re*uest
processing. ,ithin error.(sp if you indicate that it is an error/processing page via the directive.
"Za page is-rrorPageQFKtrueFK Z#.
Q) <ow do I prevent the otpt of my J(P or (ervlet pa$es from bein$ cached by the Web browser? "nd Pro9y
server?
") ,eb browser caching
"Z response.set1eader(K2ache/2ontrolKKno/storeK)M
response.set1eader(KPragmaKKno/cacheK)M
response.set3ate1eader (K-xpiresK ?)M
Z#
Proxy server caching
response.set1eader(K2ache/2ontrolKKprivateK)M
Q) WhatGs a better approach for enablin$ thread.safe servlets % J(Ps? (in$le+hread'odel Interface or
(ynchroni6ation?
") SingleThread)odel techni*ue is easy to use and wor's well for low volume sites. $f your users to increase in the
future you may be better off implementing explicit synchroni!ation for your shared data
Also note that SingleThread)odel is pretty resource intensive from the serverJs perspective. The most serious issue
however is when the number of concurrent re*uests exhaust the servlet instance pool. $n that case all the unserviced
re*uests are *ueued until something becomes free.
Q) Invo)in$ a (ervlet from a J(P pa$e? Passin$ data to a (ervlet invo)ed from a J(P pa$e?
") Rse "(sp.forward pageQK%relativepath%8ourServletK %#
!or)
response.sendHedirect(Khttp.%%path%8ourServletK).
7ariables also can be sent as.
"(sp.forward pageQ%relativepath%8ourServlet#
"(sp.param nameQKname>K valueQKvalue>K %#
"(sp.param nameQKname9K valueQKvalue9K %#
"%(sp.forward#
8ou may also pass parameters to your servlet by specifying response.sendHedirect(Khttp.%%path%8ourServlet+
param>Qval>K).
Q) J(P. to.EJ0 (ession 0ean commnication?
"Za page importQK(avax.naming.X (avax.rmi.PortableHemote&b(ect foo.Account1ome foo.AccountK Z#
"ZW
Account1ome acc1omeQnullM
public void (sp$nit() L
$nitial2ontext cntxt Q new $nitial2ontext( )M
&b(ect refQ cntxt.loo'up(K(ava. comp%env%e(b%Account-JCK)M
acc1ome Q (Account1ome)PortableHemote&b(ect.narrow(refAccount1ome.class)M
N
Z#
"Z
Account acct Q acc1ome.create()M
acct.do,hatever(...)M
Z#
Q) <ow do yo pass an InitParameter to a J(P?
"ZW
Servlet2onfig cfg QnullM
public void (sp$nit()L
Servlet2onfig cfgQgetServlet2onfig()M
for (-numeration eQcfg.get$nitParameter0ames()M e.has)ore-lements()M)
L
String nameQ(String)e.next-lement()M
String value Q cfg.get$nitParameter(name)M
System.out.println(nameSKQKSvalue)M
N
N
Z#
Q) <ow to view an ima$e stored on database with J(P?
"Za page languageQK(avaK importQK(ava.s*l.X(ava.util.XKZ#
"Z
String imagecid Q (String) re*uest.getParameter(K$3K)M
if (imagecid WQ null)L
try
L
2lass.for0ame(Kinterbase.interclient.3riverK)M
2onnection con Q
3river)anager.get2onnection(K(dbc.interbase.%%localhost%3.%examp%3atabase%employee.gdbKK(avaKK(avaK)M
Statement stmt Q con.createStatement()M
HesultSet rs Q stmt.executeYuery(KS-@-2T X AH&) $))A4$0- ,1-H- $))A4$0-c$3 Q K S imagecid)M
if (rs.next())
L
String dimcimage Q rs.getString(K$))A4$0-c3$)-0S$&0-K)M
byte OP blocco Q rs.getCytes(K$))A4$0-c$))A4$0-K)M
response.set2ontentType(Kimage%(pegK)M
Servlet&utputStream op Q response.get&utputStream()M
for(int iQ?Mi"$nteger.parse$nt(dimcimage)MiSS)
L
op.write(bloccoOiP)M
N
N
rs.close()M
stmt.close()M
con.close()M
N catch(-xception e) L
out.println(KAn error occurs . K S e.toString())M
N
N
Z#
Q) <ow do I pass vales from a list bo9 !with mltiple selects) to a Java 0ean?
2onsider the following 1T)@ which basically allows the user to select multiple values by means of a chec'box.
,hatJs your favorite movie+
"form methodQpost actionQ)ovies.(sp#
"input typeQchec'box nameQfave)ovies valueQK9??>. A Space &dysseyK# 9??>. A Space &dyssey
"input typeQchec'box nameQfave)ovies valueQKThe ,aterboyK# The ,aterboy
"input typeQchec'box nameQfave)ovies valueQKThe Tin 3rumK# The Tin 3rum
"input typeQchec'box nameQfave)ovies valueQKCeing JohnK# Ceing John )al'ovich
"input typeQsubmit#
"%form#
To handle 1T)@ elements li'e chec'boxes and lists which can be used to select multiple values you need to use a
bean with indexed properties (arrays). The following bean can be used to store the data selected from the above chec'
box since it contains an indexed property movies.
pac'age fooM
public class )ovieCean L
private StringOP moviesM
public )ovieCean() L
String moviesOP Q new StringO?PM
N
public StringOP get)ovies() L
return moviesM
N
public void set)ovies(StringOP m) L
this.movies Q mM
N
N
Although a good design pattern would be to have the names of the bean properties match those of the 1T)@ input form
elements it need not always be the case as indicated within this example. The JSP code to process the posted form
data is as follows.
"html# "body#
"ZW StringOP moviesM Z#
"(sp.useCean idQKmovieCeanK classQKfoo.)ovieCeanK#
"(sp.setProperty nameQKmovieCeanK propertyQKmoviesK paramQKfave)oviesK %#
"%(sp.useCean#
"Z movies Q movieCean.get)ovies()M
if (movies WQ null) L
out.println(K8ou selected. "br#K)M
out.println(K"ul#K)M
for (int i Q ?M i " movies.lengthM iSS) L
out.println (K"li#KSmoviesOiPSK"%li#K)M
N
out.println(K"%ul#K)M
N else
out.println (K3onJt you watch any movies+WK)M
Z#
"%body#"%html#
Q) +a$ Dibraries
These all methods are callbac' methods.
Tag methods. doStartTag()
do-ndTag()
Cody Tag . doAfterCody()
EEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEE
J#0C Qestions
Q) What Class*for-ame will do while loadin$ drivers?
") ,ill create an instance of the driver and register with the 3river)anager.
Q) J#0C A*L new featres?
") >. 8ransaction (avepoint support. / Added the Savepoint interface which contains new methods to set release or
roll bac' a transaction to designated savepoints.
9. Heuse of prepared statements by connection pools. / to control how prepared statements are pooled and reused by
connections.
<. 2onnection pool configuration ./ 3efined a number of properties for the 2onnectionPool3ataSource interface.
These properties can be used to describe how Pooled2onnection ob(ects created by 3ataSource ob(ects should be
pooled.
U. Hetrieval of parameter metadata. / Added the interface Parameter)eta3ata which describes the number type
and properties of parameters to prepared statements.
B. Hetrieval of auto/generated 'eys. / Added a means of retrieving values from columns containing automatically
generated values.
;. Multiple open 4esult(et objects. / Added the new method get)oreHesults(int).
D. Passing parameters to 2allableStatement ob(ects by name. / Added methods to allow a string to identify the
parameter to be set for a 2allableStatement ob(ect.
^. 1oldable cursor support. / Added the ability to specify the of holdability of a HesultSet ob(ect.
V. )OO'*- data type. / Added the data type (ava.s*l.Types.C&&@-A0. C&&@-A0 is logically e*uivalent to C$T.
>?. )a'ing internal updates to the data in Clob and 2lob ob(ects. / Added methods to allow the data contained in Clob
and 2lob ob(ects to be altered.
>>. Hetrieving and updating the ob(ect referenced by a Hef ob(ect. / Added methods to retrieve the ob(ect referenced by
a Hef ob(ect. Also added the ability to update a referenced ob(ect through the Hef ob(ect.
>9. +pdating o" columns containing )'O), C'O), 44@ and 4*& types. / Added of the updateClob update2lob
updateArray and updateHef methods to the HesultSet interface.
Q) J#0C #rivers
o J3C2/&3C2 Cridge 3river
o 0ative AP$ / Partly Java 3river
o 0etwor' protocol / All Java 3river
o 0ative Protocol / Pure Java 3river
Tier 3river mechanism 3escription
Two J3C2/&3C2
J3C2 access via most &3C2 drivers some &3C2 binary code and
client code must be loaded on each client machine. This driver is
commonly used for prototyping. The J3C2/&3C2 Cridge is J3C2
driver which implements J3C2 operations by translating them to
&3C2 operations.
Two 0ative AP$ / Partly Java driver
This driver converts J3C2 calls to database specific native calls.
2lient re*uires database specific libraries.
Three 0etwor' protocol / All Java 3river
This driver converts J3C2 calls into 3C)S independent networ'
protocol that is sent to the middleware server. This will translate this
3C)S independent networ' protocol into 3C)S specific protocol
which is sent to a particular database. The results are again rooted
bac' to middleware server and sent bac' to client.
Two 0ative protocol / All / Java driver
They are pure (ava driver they communicate directly with the
vendor database.
Q) J#0C connection
import (ava.s*l.XM
public class J3C2Sample L
public static void main((ava.lang.StringOP args) L
try L
2lass.for0ame(Ksun.(dbc.odbc.Jdbc&dbc3riverK)M
N catch (2lass0otAound-xception e) L
System.out.println(KRnable to load 3river 2lassK)M
returnM
N
try L
2onnection con Q 3river)anager.get2onnection(K(dbc.odbc.companydbKKK KK)M
Statement stmt Q con.createStatement()M
HesultSet rs Q stmt.executeYuery(KS-@-2T A$HSTc0A)- AH&) -)P@&8--SK)M
while(rs.next()) L
System.out.println(rs.getString(KA$HSTc0A)-K))M
N
rs.close()M
stmt.close()M
con.close()M
N
catch (SY@-xception se) L
System.out.println(KSY@ -xception. K S se.get)essage())M
N
N
N
Q) H
th
type driver
class.for0ame(5oracle.(dbcdriver.oracledriver6)M
connection con Q driver)anager.get2onnection(5J3C2.oracle.thin.ahostname.portno.oracleservice66uid6 5pwd6)M
Q) (teps to connect to J#0C?
") ?* Airst thing is using (dbc you have to establish a connection to the data base this is 9 steps process (i) you must
load the (dbc driver (ii) then ma'e a connection to do this we can call the get2onnection() method of driver manager
class.
@* To execute any s*l commands using (dbc connection you must first create a statement ob(ect to create this call
statement st Q con.createSteatement().
This is done by calling the createStatement() method in connection interface. &nce the statement is created you can
executed it by calling execute() method of the statement interface.
Q) 1esltset +ypes
rs.beforeAirst() goto >
st
record
rs.after@ast() goto last record
isAirst() I is@ast()
res.absolute(U) will got U
th
record in result set.
rs.deleteHow()
rs.updateHow(<^^) value in column < of resultset is set to ^^.
rs.updateAloat()
rs.relative(9)
Q) +ransactional (avepoints
Statement stmt Q conn.createStatement ()M
$nt rowcount Q stmt.executeRpdate (Kinsert into etable (event) values (JT))J)K)M
$nt rowcount Q stmt.executeRpdate (Kinsert into costs (cost) values (UB.?)K)M
Savepoint sv> Q conn.setSavePoint (Ksvpoint>K)M %% create save point for inserts
$nt rowcount Q stmt.executeRpdate (Kdelete from employeesK)M
2onn.rollbac' (sv>)M %% discard the delete statement but 'eep the inserts
2onn.commitM %% inserts are now permanent
Q) 7pdatin$ 0DO0 % CDO0 #ata +ypes
rs.next()M
Clob data Q rs.get2lob (>)M
Hs.close()M
%% now letJs insert this history into another table
stmt.set2lob (> data)M %% data is the 2lob ob(ect we retrieved from the history table
int $nsert2ount Q stmt.executeRpdate(Kinsert into -scalated$ncidents ($ncident$3 2ase1istory &wner)K
S K 7alues (D>>;U + J4oodsonJ) K)M
Q 1etreivin$ % (torin$ I 7pdatin$ "rray of Ob&ects
Array a Q rs.getArray(>)M
Pstmt.setArray(9 membercarray)M
Hs.updateArray(5lastcnum6num)M
Q) <ow to e9ecte no of Feries at one $o?
") Cy using a batchRpdateJs (i.e. throw addCatch() and executeCatch()) in (ava.s*l.Statement interface or by using
procedures.
Q) 0atch 7pdates
2allableStatement stmt Q con.prepare2all(5Lcall employee$nfo (+)N6)M
stmt.addCatch(K$0S-HT $0T& employees 7A@R-S (>??? JJoe JonesJ)K)M
stmt.addCatch(K$0S-HT $0T& departments 7A@R-S (9;? JShoeJ)K)M
%% submit a batch of update commands for execution
intOP update2ounts Q stmt.executeCatch()M
Q) 'ltiple 1esltset
") The methods get)oreHesults getRpdate2ount and getHesultSet can be used to retrieve all the results.
2allableStatement cstmt Q connection.prepare2all(proc2all)M
boolean retval Q cstmt.execute()M
if (retval QQ false) L
N else L
HesultSet rs> Q cstmt.getHesultSet()M
retval Q cstmt.get)oreHesults(Statement.I--Pc2RHH-0TcH-SR@T)M
if (retval QQ true) L
HesultSet rs9 Q cstmt.getHesultSet()M
rs9.next()M
rs>.next()M
N
N
2@&S-cA@@cH-SR@TS All previously opened HesultSet ob(ects should be closed when calling
get)oreHesults().
2@&S-c2RHH-0TcH-SR@T The current HesultSet ob(ect should be closed when calling
get)oreHesults().
I--Pc2RHH-0TcH-SR@T The current HesultSet ob(ect should not be closed when calling
get)oreHesults().
Q) #iff e9ecte!) 5e9ecte7pdate!) and e9ecteQery!) ?
") execute() returns a boolean value which may return mltiple reslts.
executeRpdate() is used for nonfetching *ueries which returns int value and tell how many rows will be affected.
executeYuery() is used for fetching *ueries which returns sin$le 1esl(et ob(ect and never return 0ull value.

Q) <ow to move the crsor in scrollable resltset?
+ype of a ResultSet object!
"#$E%&'R()R*%'+,#, "#$E%S-R',,%.+SE+S."./E, "#$E%S-R',,%SE+S."./E,
-'+-0R%RE)*%'+,# and -'+-0R%0$*)")1,E.
Statement stmt Q con.createStatement(HesultSet.T8P-cS2H&@@cS-0S$T$7-
HesultSet.2&02RHcH-A3c&0@8)M
HesultSet rs Q stmt.executeYuery(KS-@-2T 2&@R)0c> 2&@R)0c9 AH&) TAC@-c0A)-K)M
rs.after@ast()M
while (srs.previous()) L
String name Q rs.getString(K2&@R)0c>K)M
float salary Q rs.getAloat(K2&@R)0c9K)M
rs.absolute(U)M %% cursor is on the fourth row
int row0um Q rs.getHow()M %% row0um should be U
rs.relative(/<)M
int row0um Q rs.getHow()M %% row0um should be >
rs.relative(9)M
int row0um Q rs.getHow()M %% row0um should be <
%%...
N
Q) <ow to :7pdate; % :#elete; a resltset pro$rammatically?
Rpdate. /
Statement stmt Q con.createStatement(HesultSet.T8P-cS2H&@@cS-0S$T$7-
HesultSet.2&02RHcRP3ATAC@-)M
HesultSet uprs Q stmt.executeYuery(KS-@-2T 2&@R)0c> 2&@R)0c9 AH&) TAC@-c0A)-K)M
uprs.last()M
uprs.updateAloat(K2&@R)0c9K 9B.BB)M%%update last rowJs data
uprs.updateHow()M%%donJt miss this method otherwise the data will be lost.

3elete. /
uprs.absolute(B)M
uprs.deleteHow()M %% will delete row B.
Q) J#0C connection pool
,hen you are going to caret a pool of connection to the database. This will give access to a collection of
already opened data base connections which will reduce the time it ta'es to service the re*uest and you can service 5n6
number of re*uest at once.
Q) Why yo need J#0C if O#0C is available?
") &3C2 is purely written in 5c6 so we cannot directly connect with (ava. J3C2 is a low level pure (ava AP$ used to
execute SY@ statements. (i) &3C2 is not appropriate for direct use from (ava because it uses 5c6 interfaces. 2alls from
(ava to native 5c6 code has number of drawbac's in the security implementation and robustness.
Q) Can we establish the connection with O#0C itself?
") 8es using (ava native classes we have to write a program.
Q) What is necessity of J#0C in J#0C.O#0C brid$e?
") The purpose of J3C2 is to lin' (ava AP$ to the &3C2 &3C2 return high level 5c6 AP$ so the J3C2 converts 5c6 level
AP$ to (ava AP$.
Q) #oes the J#0C.O#0C 0rid$e spport mltiple concrrent open statements per connection?
") 0o. 8ou can open only one Statement ob(ect per connection when you are using the J3C2/&3C2 Cridge.
Q) Is the J#0C.O#0C 0rid$e mlti.threaded?
") 0o. The J3C2/&3C2 Cridge does not support concurrent access from different threads. The J3C2/&3C2 Cridge
uses synchroni!ed methods to seriali!e all of the calls that it ma'es to &3C2
Q) #ynamically creatin$ +ables
Statement st Q con.cretaeStatement()M
$nt n Q st.executeRpdate(5create table 5 S unameS 5(sno int sentby varchar(>?) sub(ect varchar(>B)6)M
Q) (tatements in J#0C
(tatement 3oes not ta'e any arguments $n this statement it will chec' syntax error and execute it every
time (it will parse every time).
Prepare statement P.S are precompiled statements once we compile the statements and send it to the server for
later use. P.S are partially compiled statements placed at server side with placeholders. Cefore execution of these
statements user has to supply values for place holders it will increase performance of application.
PreparedStatement pst Q con.prepareStatement(KS-@-2T X AH&) -)P ,1-H- deptnoQ+K)M
3ata$nputStream dis Q new 3ata$nputStream(5System.in6)M
$nt dno Q $nteger.Parse$nt(dis.read@ine())M
pst.set$nt(> dno)M
HesultSet rs Q pst.executeYuery()M
Callable statement 2.S used to retrieve data by invo'ing stored procedures stored procedure are program units
placed at data base server side for reusability. These are used by n/number of clients. Stored procedure is precompiled
in H3C)S so they can run faster than the dynamic s*l.
2allable statement will call a single stored procedure they perform multiple *ueries and updates without networ' traffic.
callableStatement cst Q con.prepare2all(5L2A@@ procedure/name(++)N 6)M
3ata$nputStream dis Q new 3ata$nputStream(5System.in6)M
$nt enum Q $nteger.Parse$nt(dis.read@ine())M
cst.set$nt(> enum)M
cst.register&utParameter(9 types.7AH21AH)
resultset rs Q cst.execute()M
$n used to send information to the procedure.
&ut used to retrieve information from data base.
$n&ut both.
Q) In which interface the methods commit!) % rollbac)!) savepoint!) defined ?
A) (ava.s*l.2onnection interface
Q) 1etrievin$ very lar$e vales from database?
A) get)SS-..Steram2) read values which are character in nature.
3et1inar4Stream2) used to read images.
Q) 1eslt(et'eta#ata
$t is used to find out the information of a table in a data base.
HesultSet rs Q stmt.executeYuery(KS-@-2T X AH&) KS table)M
HesultSet)eta3ata rsmd Q rs.get)eta3ata()M
)ethods get2olumn2ount() get2olumn0ame() get2olumn@abel() get2olumnType() getTable0ame()
Q) #atabase 'eta#ata
8ou need some information about the 5data base6 T 5dictionary6 we use this .To find out tables stored procedure
names columns in a table primary 'ey of a table we use this this is the lar$est interface in (ava.s*l pac'age
2onnection con Q 3river)anager.get2onnection((dbcRH@ KK KK)M
3atabase)eta3ata dbmd Q con.get)eta3ata()M
HesultSet rsQ dbmd.getxxx()M
)ethods get2olumns() getTableTypes() getTables() get3river0ame() get)a(or7ersion() get )inor7ersion()
getProcedures() getProcedure2olumns() getTables().
Q) (QD Warnin$s
,arnings may be retrieved from 2onnection Statement and HesultSet ob(ects. Trying to retrieve a warning on a
connection after it has been closed will cause an exception to be thrown. Similarly trying to retrieve a warning on a
statement after it has been closed or on a result set after it has been closed will cause an exception to be thrown. 0ote
that closing a statement also closes a result set that it might have produced.
2onnection.get,arnings()
Statement.get,arnings()
HesultSet.get,arnings() Seriali!ed Aorm
SY@,arning warning Q stmt.get,arnings()M
if (warning WQ null)
L
while (warning WQ null)
L
System.out.println(K)essage. K S warning.get)essage())M
System.out.println(KSY@State. K S warning.getSY@State())M
System.out.print(K7endor error code. K)M
System.out.println(warning.get-rror2ode())M
warning Q warning.get0ext,arning()M
N
N
Q) Procedre
Procedure is a subprogram will perform some specific action sub programs are name P@%SY@ bloc's that can
ta'e parameters to be invo'ed.
create (or) replace procedure procedure/name (id $0 $0T-4-H bal $0 &RT A@&AT) $S
C-4$0
select balance into bal from accounts where accountcid Q idM
Cal. Q bal S bal X ?.?<M
Rpdate accounts set balance Q bal where accountcid Q idM
-03M
Q) +ri$$er
Trigger is a stored P@%SY@ bloc' associated with a specific database table. &racle executes triggers
automatically when ever a given SY@ operation effects the table we can associate >9 data base triggers with in a given
table.
2reate%Heplace trigger before $nsert (or) 3elete (or) Rpdate on emp for each row
Cegin
$nsert into table/name values(.empnoM .name)
end
Q) (tored Ima$es into a table

Public class img
L
Public static void main(String argsOP)L
2lass.for0ame()M
2onnection con Q 3river)anager.get2onnection()M
Preparestatement pst Q con.prepareStatement(5insert into image value(+))M
Aile$nputStream fis Q new Aile$nputStream(5a.gif6)M
Pst.setCinaryStream(> fis fis.available)M
$nt $ Q pst.executeRpadate()M
N
1etrieve Ima$e
Statement st Q con.2reateStatement()M
HesultSet rs E st.executeYuery(5select X from img6)M
Hs.next()M
$nputStream is Q rs.getCinaryStream(>)M
Aile&utPutStream fos Q new Aile&utPutStream(5g9.gif6)M
$nt chM
,hile((chQis.read(>))WQW/>)
L
fos.write(ch)M
N
+hreadin$ Qestions
Q) What threads will start when yo start the &ava pro$ram?
") Ainali!er )ain Heference 1andler Signal dispatcher.
Q) +hread
Thread is a smallest unit of dispatchable code.
Q) #iff process and threads?
") Thread is a smallest unit of dispatchable code Process is a sub program will perform some specific actions.
($) Process is a heavy weight tas' and is more cost. (ii) Thread is a lightweight tas' which is of low cost.
(iii) A Program can contain more than one thread. (v) A program under execution is called as process.
Q) (leep!)5 wait!)5 notify!)5 notify"ll!)5 stop!)5 sspend!)5 resme!)
sleep sleep for a thread until some specific amount of time.
wait wait for a thread until some specific condition occurs !Or) Tells the calling thread to give up the
monitor and go to sleep until some other thread enters the same monitor and calls notify().
notify! ) wa'es up the first thread that called wait() on the same ob(ect.
notify"ll! ) wa'es up all the threads that called wait() on the same ob(ect the highest priority thread will run first.
stop! ) The thread move to dead state.
sspend! ) % resme! ) To pass and restart the execution of a thread. $n case of suspend thread will be suspended
by calling the loc' on the ob(ect. Hesume will restart from where it is suspended.
&oin! ) wait for a thread to terminate.
Q) Vield! )
8ield method temporarily stop the callers thread and put at the end of *ueue to wait for another turn to be
executed. $t is used to ma'e other threads of the same priority have the chance to run.
Thread.sleep(milliseconds)M
Thread.sleep(milliseconds nanoseconds)M
Q) 'lti +hreadin$
)ultithreading is the mechanism in which more than one thread run independent of each other within the
process.
Q) #aemon +hread
3aemon thread is one which serves another thread it has no other role normally a daemon thread carry some
bac'ground program. ,hen daemon thread remains the program exist.
Q) +hread Priority
)$0cPH$&H$T8 Q >
0&H)cPH$&H$T8 Q B
)A`cPH$&H$T8 Q >?
Q) Can I restart a stopped thread?
") &nce a thread is stopped it cannot be restarted. Ieep in mind though that the use of the stop() method of Thread is
deprecated and should be avoided.
Q) +hread Priorities
2lass A implements HunnableL
Thread tM
Public clic'er(int p)L
T Q new Thread(this)
t.setPriority(p)M
N
public void run()L
N
public void stop()L
N
public void start()L
t.start()M
N
tryL
thread.sleep(>???)M
N
lo.stop()M
hi.stop()M
tryL
hi.t.(oin()M
lo.t.(oin()M
N
class 1i@oL
public static void main(Stirng argsOP)L
Thread.currentThread().setPriority(Thread.)A`cPH$&H$T8)M
2lic'er hi Q new 2lic'er(Thread.0&H)cPH$&H$T8S9)M
2lic'er lo Q new 2lic'er(Thread.0&H)cPH$&H$T8/9)M
@o.start()M
1i.start()M
Q) What is the se of start!) fnction in startin$ a thread? why we do not se the rn!) method directly to rn
the thread?
Start method tell the J7) that it needs to create a system specific thread. After creating the system resources it
passes the runnable ob(ect to it to execute the run() method.
2alling run() method directly has the thread execute in the same as the calling ob(ect not a separate thread of
execution.
Q) What are the different levels of loc)in$ sin$ W(ynchroni6eQ )ey word?
") 2lass level method level ob(ect level bloc' level
Q) Which attribte are thread safe?
Ob&ective 'lti +hreaded 'odel (in$le threaded 'odel
@ocal variables V V
$nstance variables - V
2lass variables - -
He*uest attributes V V
Session attributes - -
2ontext attributes - -
EJ0 Qestions
Q> What is the J@EE?
The J9-- is a set of coordinated specifications and practices that together enable solutions for developing deploying
and managing multi/tier server/centric applications.
Q) What is enterprise &ava bean? Why e&b?
") $tGs a collection of (ava classes and xml descriptor files bundled together as a unit. The (ava classes must provide
certain rules and call bac' methods as per e(b specifications.
,hen the application is so complex and re*uires certain enter prise level services such as concurrency scalability
transaction services resource pooling security fail/over load/balancing e(b is the right choice.
Q) -ew in EJ0 @*??
)essage/driven beans ()3Cs). can now accept messages from sources other than J)S.
-JC *uery language (-JC/Y@). many new functions are added to this language. &H3-H C8 A74 )$0 )A` SR)
2&R0T and )&3.
Support for ,eb services. stateless session beans can be invo'ed over S&AP%1TTP. Also an -JC can easily access
a ,eb service using the new service reference.
-JC timer service. a new event/based mechanism for invo'ing -JCs at specific times.
)any small changes. support for the latest versions of Java specifications `)@ schema and message destinations.
Q) "pplication server % Web server
A.S is a generali!ed server for running more than one application li'e e(b rmi (sp and servlets.
,.S is for re*uest response paradigm. $t ta'es the client re*uest and send response bac' to the client and the
connection is closed.
A.S cannot process 1ttp re*uest but ta'es the forwarded re*uest from ,.S and process the business logic and send
the output to the ,.S which it turns send to the client.
,.S understands and supports only 1TTP protocol whereas an Application Server supports 1TTP T2P%$P and many
more protocols.
A.S manages transactions security persistence clustering caching but ,.S cannot help in this regards. ,.S ta'es
only the 1ttp re*uest.
A.S provides runtime environment for server side components they provide middleware services such as resource
pooling and networ'.
Q) What does Container contain?
") >. Support for Transaction )anagement 9. Support for Security <. Support for Persistence U. Support for
management of multiple instances ($nstance passivation $nstance Pooling 3atabase connection pooling)
B. @ife 2ycle )anagement
Q) (ession0eans
Session beans are not persistence there are short lived beans. S.C can perform database operations but S.C it
self is not a persistence ob(ects. S.C are business process ob(ects they implements business logic business rules and
wor'flow.
Q) (tatefll (ession 0ean % (tateless (ession 0ean
Q) Entity 0ean
-ntity beans are permanent business entities because their state is saved in permanent data storage. -.C are
persistence ob(ects -.C contain data related logic. -.C are permanent so if any machine crashes the -.C can be
reconstructed in memory again by simple reading the data bac' in from the database.
0ean mana$ed Persistence % Container mana$ed Persistence
C.P is an entity bean that must be persisted by hand other words component developer must write the code to
translate your in/memory fields into an underlying data store. 8ou handle these persist operations your self you place
your data base calls in e(b@oad() and e(bStore(). Ainder methods only for C.).P for 2.).P your e(b container will
implement the finder methods. $n this commit5 rollbac)5 be$in are transactions $n C.).P findCyPI() return a reference
to the actual bean ob(ect.
8ou do not have to do anything to synchroni!e with database. $n entity bean deployment descriptor you specify which
fields that the container should manage. The transactions in 2.).P are +J.(pport5 +J.-ot(pport5 +J.reFire. 1e
findCyPI() in 2.).P return void because the method is internally implemented.
Q) 'essa$e #riven 0ean
).3.C process messages asynchronously are deliver via J)S. ).3.CGs are stateless server side transaction aware
components used for asynchronous J)S messages. $t acts as a J)S message listener which J)S messages the
messages may be sent by any J9ee component an application client another enterprise bean or by a J)S application.
,hen -JC application server starts it parse the 3.3 and then loads and initiali!es declared beans. $n case of ).3.C
container establish a connection with the message provide()&) server) client access message beans through the
beans J)S interface ((ava.J)S.message@isterner) which exposes a single method.
Public void onmessage((avax.J)S.message message)
Q) #iff (tatefll (ession % Entity 0ean?
Coth S.S.C T -.C undergo passivation and activation. The -.C have a separate e(bStore() callbac' for saving
state during passivation T a separate e(b@oad() callbac' for loading state during activation. ,e do not need these
callbac's for S.S.C because the container is simply uses ob(ect seriali!ation to persist S.S.C fields.
Q) #iff '#0 % (tateless (ession beans?
. )3CGs process multiple J)S messages asynchronously rather than processing a seriali!ed se*uence of method calls.
/ )3C have no 1.$ % H.$ and therefore cannot be directly accessed by internal or external clients. 2lients interact with
)3CGs only indirectly by sending a message to a J)S Yueue or Topic.
! &nly the container directly interacts with a message/driven bean by creating bean instances and passing J)S
messages to those instances as necessary
/The 2ontainer maintains the entire lifecycle of a )3CM instances cannot be created or removed as a result of client
re*uests or other AP$ calls.
(tateless (ession 0ean (tatefl (ession 0ean
Stateless session bean these are sin$le reFest
business process is one that does not re*uire
state to be maintained across method invocation.
Stateless session bean cannot hold the state.
Statefull session bean is a bean that is designed to
service business process that span mltiple methods
reFestItransaction S.S.C can retain their state on the
behalf of individual client.
There should be one and only one create method
that to without any argument in the home
interface.
There can be one or more create methods with or
without arguments in the 1ome $nterface.
Stateless session bean instance can be pooled.
Therefore 5n6 number of beans can cater to nS>
number of clients.
Statefull session bean do not have pooling concept.
Stateful bean will be given individual copy for every user.
Stateless bean will not be destroyed after client
has gone.
Stateful bean will be destroyed once the client has gone
(or after session time out)
$f the business last only for a single method call
S.S.C are suitable
$f the business process spans multiple invocations there
by re*uiring a conversational then S.S.C will be ideal
choice.
Stateless session bean cannot have instance
variable
Stateful session bean will have instance variable and
state is maintained in these instance variables
-(bHemove() method does not destroy the bean
it remains in the pooled state.
Stateful bean can be destroyed by calling the
e(bHemove() method
Q) When to choose (tatefll % (tateless (ession bean?
") 3oes the business process span multiple method invocations re*uiring a conversational state if so the state full
model fits very nicely. $f your business process last for a single method call the stateless paradigm will better suite
needed.
Q) When to choose (ession 0ean % Entity 0ean?
-.C are effective when application want to access one row at a time if many rows needed to be fetched using
session bean can be better alternative.
-.C are effective when wor'ing with one row at a time cause of lot of 0., traffic. S.C are efficient when client wants
to access database directly fetching updating multiple rows from database.
S.C for application logic.
Q) When to choose C'P % 0'P?
2)P is used when the persistent data store is a relational database and there is 5one to one6 mapping
between a data represented in a table in the relational database and the e(b ob(ect.
Cean managed persistence is used when there is no 5one to one6 mapping of the table and a complex *uery
retrieving data from several tables needs to be performed to construct an e(b ob(ect. Cean managed is also used when
the persistence data storage is not a relational database.
Q) <ow do (tatefl (ession beans maintain consistency across transaction pdates?
") S.S.C maintain data consistency by updating their fields each time a transaction is committed. To 'eep informed of
changes in transation status a S.S.C implements the SessionSynchroni!ation interface. 2ontainer then calls methods
of this interface as it initiates and completes transactions involving the bean.
Q) CanGt statefl session beans persistent? Is it possible to maintain persistence temporarily in statefl
sessionbeans?
") Session beans are not designed to be persistent whether stateful or stateless. A stateful session bean instance
typically canJt survive system failures and other destructive events.
8es it is possible using 1andle.
Q) Ob&ect.1elational 'appin$
)apping of ob(ects to relational database is a technology called &.H.). &.H.) is a persistence mechanism of
persistence ob(ects than simple ob(ect seriali!ation.
Q) #eployment #escriptor
3.3 contains information for all the beans in the 5e(b.(ar6 file. 3.3 enables e(b container to provide implicit
services to enterprise bean components these services can gain your bean with out coding. 3.3 is a `)@ file.
Q) e&bCreate!)
$n stateless session bean can have only one e(b2reate() method it must ta'e no arguments. Hemember that
e(b2reate() is essentially analogous to a constructor for e(bM it initiali!es an instance internal state variable. Cecause the
stateless session bean has no client specific variables.
Q) Can a (ession 0ean be defined withot e&bCreate!) method?
The e(b2reate() methods is part of the beanJs lifecycle so the compiler will not return an error because there is no
e(b2reate() method.
/ The home interface of a Stateless Session Cean must have a single create() method with no arguments while the
session bean class must contain exactly one ejbCreate() method also without arguments.
/ Stateful Session Ceans can have arguments (more than one create method). Stateful beans can contain multiple
e(b2reate() as long as they match with the home interface definition
Q) Can I develop an Entity 0ean withot implementin$ the create!) method in the home interface?
As per the specifications there can be Jd-H&J or J)&H-J create() methods defined in an -ntity Cean. $n cases
where create() method is not provided the only way to access the bean is by 'nowing its primary 'ey and by ac*uiring
a handle to it by using its corresponding finder method. $n those cases you can create an instance of a bean based on
the data present in the table. All one needs to 'now is the primary 'ey of that table. i.e. a set a columns that uni*uely
identify a single row in that table. &nce this is 'nown one can use the JgetPrimaryIey()J to get a remote reference to
that bean which can further be used to invo'e business methods.
Q) <ow do yo determine whether two entity beans are the same?
A) Cy invo'ing the -ntityCean.is$dentical method. This method should be implemented by the entity bean developer to
determine when two references are to the same ob(ect.
Q) <ow can yo captre if find0y method retrns more than one row?
") $f finder method returns more than one row create or instantiate an ob(ect (which has instance variable e*ual to
number of columns to be stored) each time and add the ob(ect to vector that stores. 7ector stores only the memory
address not ob(ect reference. So every time when you instantiate and store ob(ect into vector a separate memory
address will be allocated and the same is stored in the vector.
Q) #iff Conte9t5 InitialConte9t % (essionConte9t % EntityConte9t
(avax.naming.2ontext is an interface that provides methods for binding a name to an ob(ect. $tJs much li'e the H)$
0aming.bind() method.
(avax.naming.$nitial2ontext is a 2ontext and provides implementation for methods available in the 2ontext interface.
,here as Session2ontext is an -JC2ontext ob(ect that is provided by the -JC container to a SessionCean in order for
the SessionCean to access the information and%or services or the container.
There is -ntity2ontext too which is also and -JC2ontext ob(ect thatJll be provided to an -ntityCean for the purpose of
the -ntityCean accessing the container details. $n general the -JC2ontext (Session2ontext and -ntity2ontext)
Applet2ontext and Servlet2ontext help the corresponding Java ob(ects in 'nowing about its JcontextJ Oenvironment in
which they runP and to access particular information and%or service. ,here as the (avax.naming.2ontext is for the
purpose of J0A)$04J Oby the way of referring toP an ob(ect.
Q) Can i call remove!) on a (tateless (ession bean?
") 8es5 The life of a Stateless Session bean for a client is (ust till the execution of the method that the client would have
called on the beaneafter the execution of that method if the client calls another method then a different bean is ta'en
from the pool. So the container very well 'nows that a bean has finished its life for a client and can put it bac' in the
pool.
Q) Can a (tateless (ession 0ean maintain state?
") 8es A Stateless Session bean can contain no.client specific state across client/invo'ed methods. Aor ex states
such as soc'et connection dbase connection references to an -JC&b(ect and so on can be maintained.
Q) <ow can I map a sin$le Entity 0ean to mltiple tables?
") $f you use 1ean-Managed 3ersistence!0'P)5 map the bean to tables manually. 2onsider applying the 3A& design
pattern to accomplish this.
$f you choose Container-Managed 3ersistence(CM3)6 use the vendors ob(ect%relational mapping tool to specify the
mapping between your ob(ect state and the persistence schema.
Q) Can EJ0 handle transaction across mltiple databases?
") The transaction manager in -JC handling transaction across multiple databases. This is accomplished with multiple
-ntity beans handling to each database and a single session bean to manage a transaction with the -ntity bean.
Q) (ession 0ean Call0ac) methods?
public interface (avax.e(b.SessionCean extends (avax.e(b.-nterpriseCean
L
public abstract void e(bActivate()M
public abstract void e(b2reate()M
public abstract void e(bPassivate()M
public abstract void e(bHemove()M
public abstract void setSession2ontext(Session2ontext ctx)M
N
(essionConte9t S.2 is your beans gateway to interact with the container S.2 *uery the container about your
current transactional state your security state.
e&bCreate!)
e&bPassivate! ) $f too many beans are instantiated the container can passivate some of them .ie write the bean to
some temp storage. The container should release all resources held by the bean. Just before passivating the container
calls the e(bPassivate() method. So release all resources here i.e. close soc'et connections..etc.
e&b"ctivate! ) ,hen a passiavted bean is called its said to be activated. The container then calls the e(bActivate()
method. Ac*uire all the re*uired resources for the bean in this method. ie get soc'et connection
e&b1emove!) container wants to remove your bean instance it will call this method.
Q) Entity 0ean Call0ac) methods?
public interface (avax.e(b.-ntityCean extends (avax.e(b.-nterpriseCean
L
public abstract void e(bActivate()M
public abstract void e(b@oad()M
public abstract void e(bPassivate()M
public abstract void e(bHemove()M
public abstract void e(bStore()M
public abstract void set-ntity2ontext(-ntity2ontext ctx)M
public abstract void unset-ntity2ontext()M
N
Q) EJ0Conte9t 1ollbac) 'ethods
-JC2ontext interface provides the methods setHollbac'&nly() T getHollbac'&nly().
set1ollbac)Only! )&nce a bean invo'es the setHollbac'&nly() method the current transaction is mar'ed for rollbac'
and cannot be committed by any other participant in the transaction//including the container.
$et1ollbac)Only! ) method returns true if the current transaction has been mar'ed for rollbac'. This can be used to
avoid executing wor' that wouldnJt be committed anyway.
Q) <ow can I call one EJ0 from inside of another EJ0?
") -JC can be clients of another -JCGs it (ust wor's. Rse J03$ to locate the 1ome $nterface of the other bean and then
ac*uire an instance.
Q) Conversational % -on.conversational
2onversational is an interaction between the bean and client stateless session bean is a bean that do not hold multi
method conversation with clients. Stateless.S.C cannot hold state Statefull.S.C can hold conversational with client that
may span multiple method re*uests.
Q) J-#I to locate <ome Ob&ects
1.& are physically located some where on the 0., perhaps in the address space of the -(b 2ontainer. Aor client to
locate 1.& you must provide nic' name for your beans 1.&. 2lient will use this nic' name to identify the 1.& it wants
we will specify the nice name in the 3eployment descriptor. 2ontainer will use this nic' name J03$ goes over the 0.,
to some directory service to loo' for the 1.&.

Properties props Q System.getProperties()M
2ontext ctx Q new $nitial2ontext(props)M
)y1ome home Q ()y1ome)ctx.loo'up(5)y1ome6)M
)yHemote$nterface remote Q home.create()M
Q) e&bCretae! ) % e&bPostCreate! )
e(b2reate() is called (ust before the state of the bean is written to the persistence storage. After this method is
completed a new record is created and written.
e(bPost2reate() is called after the bean has been written to the database and the bean data has been assigned to
an -(b ob(ect.
Q) E"15 W"15 J"1
All -JC classes should pac'age in a JAH file All web components pages servlets gif html applets beans e(b
modules classes should be pac'aged into ,AH file. -AH file contain all the JAH T ,AH files. 0ote that each JAH
,AH -AH file will contain 3.3
Q) What is the need of 1emote and <ome interface* Why cant it be in one?
The home interface is your way to communicate with the container that is who is responsible of creating locating even
removing one or more beans. The remote interface is your lin' to the bean that will allow you to remotely access to all
its methods and members. As you can see there are two distinct elements (the container and beans) and you need two
different interfaces for accessing to both of them.
Q) D ife cycle
D ife cycle of a (tatefl (ession 0ean
- Stateful session bean has < states =oes -ot *xist, Method 4eady ,ool and ,assivated states.
- A bean has not yet instantiated when it is in the =oes -ot *xist (ate.
- &nce a container creates one are more instance of a Stateful Session bean it sets them in a Method 4eady
(tate. $n this state it can serve re*uests from its clients. @i'e Stateless beans a new instance is
created(2lass.new$nstance()) the context is passed (setSession2ontext()) and finally the bean is created with
the e(b2reate().
- e&bPassivate! ) $f too many beans are instantiated the container can passivate some of them .ie write the
bean to some temp storage. The container should release all resources held by the bean. Just before
passivating the container calls the e(bPassivate() method. So release all resources hereieclose soc'et
connections..-tc.
- e&b"ctivate! ) ,hen a passiavted bean is called its said to be activated. The container then calls the
e(bActivate() method. Ac*uire all the re*uired resources for the bean in this method. ie get soc'et connection
D ife cycle of a (tateless (ession 0ean > .
- A S.S.C has only two states. =oes -ot *xist and )ethod Heady Pool.
- A bean has not yet instantiated when it is in the =oes -ot *xist (ate.
- ,hen the -JC container needs one are more beans it creates and set then in the )ethod Heady Pool Sate.
This happens through the creation of a new instance(2lass.new$nstance()) then it is set its context
(setSession2ontext()) and finally calls the e(b2reate() method.
- The e(bHemove() method is called to move a bean from the )ethod Heady Pool bac' to 3oes 0ot -xist State.
Dife cycle of Entity bean
- Cean instance 53ose not exist6 state represent entity bean instance that has not been instantiated yet.
- To create a new instance container calls the new$nstance() on entity bean class.
- After step 9 -.C is in a pool of other -.Cs. At this point your -.C does not have any -.C data base data loaded
into it and it does not hold any bean specific resources (soc'et T database connections) .$f the container wants
to reduce itGs pool si!e it can destroy your bean by calling unset-ntity2ontext() on your bean.
- ,hen the client wants to create some new data base data it calls a create() method on entity beans
1ome&b(ect. The container grabs the beans instance from the pool and the instance e(b2reate() method is
called.
- -.C to be 'ic'ed bac' to pool if a client call e(bremove() method.
- e&bPassivate! ) $f too many beans are instantiated the container can passivate some of them .ie write the
bean to some temp storage. The container should release all resources held by the bean. Just before
passivating the container calls the e(bPassivate() method. So release all resources here ieclose soc'et
connections..etc.
- e&b"ctivate! ) ,hen a passiavted bean is called its said to be activated. The container then calls the
e(bActivate() method. Ac*uire all the re*uired resources for the bean in this method. ie get soc'et connection
-
Dife cycle of '*#*0
#oes -ot E9ist
,hen an )3C instance is in the 3oes 0ot -xist state it is not an instance in the memory of the system. $n other words
it has not been instantiated yet.
+he 'ethod.1eady Pool
)3C instances enter the )ethod/Heady Pool as the container needs them. ,hen the -JC server is first started it may
create a number of )3C instances and enter them into the )ethod/Heady Pool. (The actual behavior of the server
depends on the implementation.) ,hen the number of )3C instances handling incoming messages is insufficient more
can be created and added to the pool.
+ransitionin$ to the 'ethod.1eady Pool
,hen an instance transitions from the 3oes 0ot -xist state to the )ethod/Heady Pool three operations are performed
on it. Airst the bean instance is instantiated when the container invo'es the 2lass.new$nstance() method on the )3C
class. Second the set)essage3riven2ontext() method is invo'ed by the container providing the )3C instance with a
reference to its -JC2ontext. The )essage3riven2ontext reference may be stored in an instance field of the )3C.
Ainally the no/argument e(b2reate() method is invo'ed by the container on the bean instance. The )3C has only one
e(b2reate() method which ta'es no arguments. The e(b2reate() method is invo'ed only once in the life cycle of the
)3C.
Q) +ransaction Isolation levels
+1"-("C+IO-R1E"#R7-CO''I++E#
The transaction can read uncommitted data. 3irty reads nonrepeatable reads and phantom reads can occur. Cean
methods with this isolation level can read uncommitted change.
+1"-("C+IO-R1E"#RCO''I++E#
The transaction cannot read uncommitted dataM data that is being changed by a different transaction cannot be read.
3irty/reads are preventedM nonrepeatable reads and phantom reads can occur. Cean methods with this isolation level
cannot read uncommitted data.
+1"-("C+IO-R1EPE"+"0DER1E"#
The transaction cannot change data that is being read by a different transaction.
3irty reads and nonrepeatable reads are preventedM phantom reads can occur. Cean methods with this isolation level
have the same restrictions as 4ead Committed and can only execute repeatable reads.
+1"-("C+IO-R(E1I"DIN"0DE
The transaction has exclusive read and update privileges to dataM different transactions can neither read nor write the
same data. 3irty reads nonrepeatable reads and phantom reads are prevented. This isolation level is the most
restrictive.
#irty.read ,hen your application reads data from a database that has not been committed to permanent storage
yet.
7n.repeatable read ,hen a component reads some data from a database but upon reading the data the data has
been changed. This can arise when another concurrently executing transaction modifies the data being read.
Phantom.read Phantom is a new set of data that magically appears in a database between two databases read
operations.
Q) #iff Phantom % 7n.repeatable
Rn/repeatable occurs when existing data is changed where as phantom read occurs when new data is inserted
that does not exist before.
Q) +ransaction "ttribtes
+JR0E"-R'"-"8E# Then your bean programmatically controls its own transaction boundaries. ,hen you using
programmatically transaction you issue the begin commit T abort statements.
+JR-O+R(7PPO1+E# $f you set this your bean cannot be involved in a transaction at all.
+JR1EQ7I1E# $f you want your bean to always run in a transaction. $f there is a transaction already running your bean (oins in on
that transaction. $f there is no transaction running the container starts one for you.
+JR1EQ7I1E(R-EW $f you always want a new transaction to begin when your bean is called we should use this. $f there is a
transaction already underway when your bean called that transaction is suspended during the bean invocation. The container then
launches a new transaction and delegate the call to the bean.
+JR(7PPO1+( ,hen a client call this it runs only in a transaction if the client had one running alreadyM it then (oins that
transaction. $f no transaction the bean runs with no transaction at all.
+JR'"-#"+O1V $s a safe transaction attribute to use. $t guarantees that your bean should run in a transaction. There is no way
your bean can be called if there is not a transaction already running.
Q) "CI# Properties
,hen you properly use transaction your operations will execute A2$3 properties.
"tomicity 4uarantees that many operations are bundled together and appears as one contiguous unit of wor'.
-x./ ,hen you transfer money from one ban' account to another you want to add funds to one account and remove
funds from the other transaction and you want both operations to occur or neither to occur.
Consistency 4uarantees that a transaction will leave the system state to be consistent after a transaction
completes.
-x. / A ban' system state could be consist if the rule 5ban' account balance must always be Sve6.
Isolation Protect concurrently executing transaction from seeing each other incomplete results.
-x. / $f you write a ban' account data to a database the transaction may obtain loc's on the ban' account record (or)
table. The loc' guarantee that no other updates can interfere.
#rability Hesources 'eep a transactional log for resources crashesM the permanent data can be reconstructed by
reapplying the steps in the log.
Q) #iff (a9 % #O'
#O' ("J
>. Tree of nodes
9. &ccupies more memory preferred for
small `)@ documents
<. Slower at runtime
U. Stored as ob(ects
B. Programmatically easy since ob(ects
;. -asy of navigation
D. 3&) creates a tree structure in memory
>.Se*uence of events
9.3oes not use any memory preferred for large
documents.
<.Aaster at runtime
U.&b(ects are to be created
B.0eed to write code for creating ob(ects are to
referred
;.bac'ward navigation is not possible
Q) <ot deployment
1ot 3eployment in ,eb @ogic is he acts of deploying re/deploying and un/deploying -JCs while the server is still
running.
Q) When shold I se +9#ata(orce instead of #atasorce?
$f your application (or) environment meets the following criteria you should use
/ Rses JTA
/ Rses -JC container in web logic server to manage transactions.
/ $ncludes multiple database updates with single transaction.
/ Access multiple resources such as database T J)S during transactions.
/ Rse same connection pool on multiple servers.
Q) Clsterin$
$n J9ee container can be distributed a distributed container consists of number of J7)Gs running on one are
more host machines. $n this setup application components can be deployed on a number of J7)Gs. Sub(ect to the type
of loading strategy and the type of the component the container can distributed the load of incoming re*uest to one of
these J7)Gs.
Q <ow to deploy in J@EE !i*e Jar5 War file)?

-ach web application should be contained in a war (web archive) file. ,ar files are nothing but a (ar file containing
atleast one descriptor called web.xml. The file structure of war file is.

%//
]
] ,-C/$0A
] ]
] ]// ,-C.`)@ (3eployment descriptor)
] ]// classes (Aolder containing servlets and JSPs
]
] )-TA/$0A
] ]
] ]// )A0$A-ST.)A
]
] all utility files and resources li'e error pages etc.

-ach enterprise bean is stored in a (ar file. The (ar file contains all standard files li'e manifest and atleast one additional
file called e(b/(ar.xml. The structure of a (ar file is.

%//
]
] )-TA/$0A
] ]
] ]// )A0$A-ST.)A
] ]// e(b/(ar.xml
]
] all classes as in a normal (ar file.

Coth (ar and war files are placed inside a ear (enterprise archive) file. The structure of an ear file is

%//
]
] )-TA/$0A
] ]
] ]// )A0$A-ST.)A
] ]// application.xml
]
] (ar and war files.
Q) <ow do yo confi$re a session bean for bean.mana$ed transactions?
") Cy set transaction/attribute in the xml file or in the deployment descriptor.
Q) #eployment descriptor of EJ0 !e&b.&ar*9ml)
"+xml versionQK>.?K+#
"W3&2T8P- e(b/(ar PRC@$2 K/%%Sun )icrosystems $nc.%%3T3 -nterprise
JavaCeans >.>%%-0K Khttp.%%(ava.sun.com%(9ee%dtds%e(b/(arc>c>.dtdK#
"e(b/(ar#
"description#
This 3eployment includes all the beans needed to ma'e a reservation.
TravelAgent ProcessPayment Heservation 2ustomer 2ruise and 2abin.
"%description#
"enterprise/beans#
"session#
"e(b/name#TravelAgentCean"%e(b/name#
"remote#com.titan.travelagent.TravelAgent"%remote#
...
"%session#
"entity#
"e(b/name#2ustomerCean"%e(b/name#
"remote#com.titan.customer.2ustomer"%remote#
...
"%entity#
"%enterprise/beans#
BK O +ransactions in EJ0 .. C
"assembly/descriptor#
"container/transaction#
"method#
"e(b/name#-JC0ame"%e(b/name#
"method/name#method0ame % X"%method/name#
"%method#
"trans/attribute#1eFired"%trans/attribute#
"%container/transaction#
"%assembly/descriptor#
...
"%e(b/(ar#
Q) Weblo$ic.e&b.&ar*9ml
"weblogic/e(b/(ar#
"weblogic/enterprise/bean#
"e(b/name#demo.Story"%e(b/name#
"entity/descriptor#
"entity/cache#
"max/beans/in/cache#>??"%max/beans/in/cache#
"idle/timeout/seconds#;??"%idle/timeout/seconds#
"read/timeout/seconds#?"%read/timeout/seconds#
"concurrency/strategy#3atabase"%concurrency/strategy#
"%entity/cache#
"lifecycle#
"passivation/strategy#default"%passivation/strategy#
"%lifecycle#
"persistence#
"delay/updates/until/end/of/tx#true"%delay/updates/until/end/of/tx#
"finders/load/bean#true"%finders/load/bean#
"persistence/type#
"type/identifier#,eb@ogicc2)PcH3C)S"%type/identifier#
"type/version#B.>.?"%type/version#
"type/storage#)-TA/$0A%weblogic/rdbms>>/persistence/;??.xml"%type/storage#
"%persistence/type#
"db/is/shared#true"%db/is/shared#
"persistence/use#
"type/identifier#,eb@ogicc2)PcH3C)S"%type/identifier#
"type/version#B.>.?"%type/version#
"%persistence/use#
"%persistence#
"entity/clustering#
"home/is/clusterable#true"%home/is/clusterable#
"%entity/clustering#
"%entity/descriptor#
"transaction/descriptor#
"trans/timeout/seconds#<?"%trans/timeout/seconds#
"%transaction/descriptor#
"enable/call/by/reference#true"%enable/call/by/reference#
"(ndi/name#demo.Story1ome"%(ndi/name#
"%weblogic/enterprise/bean#
"%weblogic/e(b/(ar#
Q) (ession 0ean E9ample
1emote Interface
public interface 1ello extends (avax.e(b.-JC&b(ect
L
public String hello() throws (ava.rmi.Hemote-xceptionM
N

<ome Interface
public interface 1ello1ome extends (avax.e(b.-JC1ome
L
1ello create() throws (ava.rmi.Hemote-xceptionM (avax.e(b.2reate-xceptionM
N
0ean Class
public class 1elloCean implements (avax.e(b.SessionCean
L
private Session2ontex ctxM
public void e(b2reate()M
public abstract void e(bHemove()M
public abstract void e(bActivate()M
public abstract void e(bPassivate()M
public abstract void setSession2ontext(Sessiony2ontext ctx)M
public String hello()L
System.out.println(5hello()6)M
Heturn 5hello world6M
N
Client
public class 1ello2lient
L
public static void main(String argsO P)
properties props Q system.getProperties()M
2ontext ctx Q new $nitial2ontext(props)M
&b(ect ob( Q ctx.loo'up(51ello1ome6)M
1ello1ome home Q (1ello1ome)
(avax.rmi.protableHemote&b(ect.narrow(ob( 1ello1ome.class)M
1ello hello Q home.create()M
System.out.println(hello.hello())M
1ello.remove()M
N
Q) Entity 0ean E9ample
<ome*&ava (1ome $nterface)
pac'age testM
public interface 1ome extends (avax.e(b.-JC1ome L
public String hello() throws Hemote-xceptionM
public int add(int a int b) throws Hemote-xceptionM
public 1ome&b( findCyPrimaryIey(String a) throws Hemote-xception Ainder-xceptionM
N
<elloOb&*&ava (Hemote $nterface)
pac'age testM
public interface 1ello&b( extends (avax.e(b.-JC&b(ect L
N
<ello0ean*&ava (Cean class)
pac'age testM
import (avax.e(b.XM
public class 1elloCean extends com.caucho.e(b.Abstract-ntityCean L
public String e(b1ome1ello()
L
return K1ello worldKM
N
public int e(b1omeAdd(int a int b)
L
return a S bM
N
public String e(bAindCyPrimaryIey(String 'ey) throws Ainder-xception
L
throw new Ainder-xception(Kno childrenK)M
N
N
Client
pac'age test.entity.homeM
import (avax.naming.XM
public class 1omeServlet extends 4enericServlet L
1ome homeM
public void init() throws Servlet-xception
L
try L
2ontext env Q (2ontext) new $nitial2ontext().loo'up(K(ava.comp%envK)M
home Q (1ome) env.loo'up(Ke(b%homeK)M
N catch (-xception e) L
throw new Servlet-xception(e)M
N
N
public void service(ServletHe*uest re* ServletHesponse res) throws $&-xception Servlet-xception
L
Print,riter pw Q res.get,riter()M
try L
pw.println(Kmessage. K S home.hello() S KK)M
pw.println(K> S < Q K S home.add(> <) S KK)M
pw.println(KD S > Q K S home.add(D >) S KK)M
N catch (-xception e) L
throw new Servlet-xception(e)M
N
N
N
(trts Qestions
Q) =ramewor)?
)) A framewor' is a reusable ffsemi/completeJJ application that can be speciali!ed to produce custom applications
Q) Why do we need (trts?
") Struts combines Java Servlets Java ServerPages custom tags and message resources into a unified framewor'.
The end result is a cooperative synergistic platform suitable for development teams independent developers and
everyone in between.
Q) #iff (trts?*L % ?*??
>.He*uestProcessor class 9.)ethod perform() replaced by execute() in Struts base Action 2lass
<. 2hanges to web.xml and struts/config.xml U. 3eclarative exception handling B.3ynamic ActionAorms ;.Plug/ins
D.)ultiple Application )odules ^.0ested Tags V.The Struts 7alidator 2hange to the &H& pac'age >?.2hange to
2ommons logging >>. Hemoval of Admin actions >9.3eprecation of the 4eneric3ataSource
Q) What is the difference between 'odel@ and '/C models?
$n model9 we have client tier as (sp controller is servlet and business logic is (ava bean. 2ontroller and
business logic beans are tightly coupled. And controller receives the R$ tier parameters. Cut in )72 2ontroller and
business logic are loosely coupled and controller has nothing to do with the pro(ect% business logic as such. 2lient tier
parameters are automatically transmitted to the business logic bean commonly called as ActionAorm.
So )odel9 is a pro(ect specific model and )72 is pro(ect independent.
Q) <ow to Confi$re (trts?
Cefore being able to use Struts you must set up your JSP container so that it 'nows to map all appropriate
re*uests with a certain file extension to the Struts action servlet. This is done in the web.xml file that is read when the
JSP container starts. ,hen the control is initiali!ed it reads a configuration file (struts/config.xml) that specifies action
mappings for the application while itJs possible to define multiple controllers in the web.xml file one for each application
should suffice
Q) "ction(ervlet !controller)
The class org!apache!struts!action!ction(ervlet is the called the ActionServlet. $n Struts Aramewor' this class
plays the role of controller. All the re*uests to the server go through the controller. 2ontroller is responsible for handling
all the re*uests. The 2ontroller receives the re*uest from the browserM invo'e a business operation and coordinating the
view to return to the client&
Q) "ction Class
The Action 2lass is part of the 'odel and is a wrapper around the business logic. The purpose of Action 2lass
is to translate the 3ttp(ervlet4e5uest to the business logic. To use the Action we need to Subclass and overwrite the
execute() method. $n the Action 2lass all the database%business processing are done. $t is advisable to perform all the
database related stuffs in the Action 2lass. The ActionServlet (commad) passes the parameteri!ed class to Action Aorm
using the execute() method. The return type of the execute method is Action7or-ard which is used by the Struts
Aramewor' to forward the re*uest to the file as per the value of the returned ction&or9ard ob(ect.
E9> .
pac'age com.odccom.struts.actionM
import (avax.servlet.http.1ttpServletHe*uestM
import (avax.servlet.http.1ttpServletHesponseM
public class CillingAdviceAction extends "ction L

public ActionAorward e9ecte(Action)apping mapping
ActionAorm form
1ttpServletHe*uest re*uest 1ttpServletHesponse response)
throws -xception L
CillingAdvice7& bavo Q new CillingAdvice7&()M
CillingAdviceAorm baform Q (CillingAdviceAorm)formM
3A&Aactory factory Q new )yS*l3A&Aactory()M
CillingAdvice3A& badao Q new )yS*lCillingAdvice3A&()M
Array@ist pro(ects Q badao.getPro(ects()M
re*uest.setAttribute(Kpro(ectsKpro(ects)M
return (mapping.findAorward(KsuccessK))M
N
N
Q) "ction =orm
An ActionAorm is a JavaCean that extends org.apache.struts.action.ActionAorm. ActionAorm maintains the session
state for web application and the ActionAorm ob(ect is automatically populated on the server side with data entered from
a form on the client side.
E9> .
pac'age com.odccom.struts.formM
public class CillingAdviceAorm extends "ction=orm L
private String pro(ectidM
private String pro(ectnameM

public String getPro(ectid() L return pro(ectidM N
public void setPro(ectid(String pro(ectid) L this.pro(ectid Q pro(ectidM N

public Action-rrors validate(Action)apping mapping 1ttpServletHe*uest re*uest) L
Action-rrors errors Q new Action-rrors()M
if(getPro(ect0ame() QQ null ]] getPro(ect0ame().length() " >)L
errors.add(5name6 new Action-rror(5error.name.re*uired6))M
N
return errorsM
}
public void reset(Action)apping mapping 1ttpServletHe*uest re*uest)L
this.roledesc Q KKM
this.currid Q KKM
N
N
Q) 'essa$e 1esorce #efinition file
).H.3 file are simple 5*properties; file these files contains the messages that can be used in struts pro(ect.
The ).H.3 can be added in struts/config.xml file through "message/resource# tag
ex. "message/resource parameterQ6)essageHesource6#
Q) 1eset >.
This is called by the struts framewor' with each re*uest purpose of this method is to reset all of the forms data
members and allow the ob(ect to be pooled for rescue.
pblic class TestAction e9tends ActionAormL
pblic void reset(Action)apping mapping 1ttpServletHe*uest re*uest re*uest)
N
Q) e9ecte
$s called by the controller when a re*uest is received from a client. The controller creates an instance of the
Action class if one does not already exist. The frame wor' will create only a single instance of each Action class.
pblic ActionAorward execute( Action)apping mapping ActionAorm form 1ttpServletHe*uest re*uest
1ttpServletHesponse response)
Q) /alidate> .
This method is called by the controller after the values from the re*uest has been inserted into the ActionAorm.
The ActionAorm should perform any input validation that can be done and return any detected errors to the controller.
Pblic Action-rrors validate(Action)apping mapping 1ttpServletHe*uest re*uest)
Q) What is /alidator? Why will yo $o for /alidator?
7alidator is an independent framewor' struts still comes pac'aged with it.
$nstead of coding validation logic in each form beanGs validate!) method with validator you use an xml
configuration file to declare the validations that should be applied to each form bean. 8alidator supports both 5server/
side and client/side6 validations where form beans only provide 5server/side6 validations.
7lo-ing steps. /
?* Enablin$ the /alidator pl$.in> This ma'es the 7alidator available to the system.
@* Create 'essa$e 1esorces for the displaying the error message to the user.
A* #evelopin$ the /alidation rles ,e have to define the validation rules in the validation.xml for the address form.
Struts 7alidator Aramewor' uses this rule for generating the JavaScript for validation.
H* "pplyin$ the rles> ,e are re*uired to add the appropriate tag to the JSP for generation of JavaScript.
Using Validator Framework
Rsing the 7alidator framewor' involves enabling the 7alidator plug/in configuring 7alidatorJs two configuration
files and creating Aorm Ceans that extend the 7alidatorJs ActionAorm subclasses.
Enablin$ the /alidator Pl$.in
7alidator framewor' comes pac'aged with StrutsM 7alidator is not enabled by default. To enable 7alidator add the
following plug/in definition to your applicationJs struts-config#'ml file.
"plug/in class0ameQKorg.apache.struts.validator.7alidatorPlug$nK#
"set/property propertyQKpathnamesK valueQK%technology%,-C/$0A%validator/rules.xml
%,-C/$0A%validation.xmlK%#
"%plug/in#
This definition tells Struts to load and initiali!e the 7alidator plug/in for your application. Rpon initiali!ation the plug/in loads the
comma/delimited list of 7alidator config files specified by the pathnames property.
/alidator.rles*9ml
"form/validation#
"global#
"7alidator nameQKre*uiredK classnameQKorg.apache.struts.validator.Aield2hec'sK methodQKvalidateHe*uiredK
methodParamsQK(ava.lang.&b(ect
org.apache.commons.validator.7alidatorAction
org.apache.commons.validator.Aield
org.apache.struts.action.Action-rrors
(avax.servlet.http.1ttpServletHe*uestK
msgQKerrors.re*uiredK#
"(avascript#
"WO23ATAO
function validateHe*uired(form) L
PP#
"%(avascript#
"%validator#
"%global#
"%form/validation#
Q) <ow strts validation is wor)in$?
7alidator uses the `)@ file to pic'up the validation rules to be applied to a form. $n `)@ validation re*uirements
are defined applied to a form. $n case we need special validation rules not provided by the validator framewor' we can
plug in our own custom validations into 7alidator.
The 7alidator Aramewor' uses two `)@ configuration files validator/rules.xml T validation.xml. The validator/
rules.xml defines the standard validation routinesM such as He*uired )inimum @ength )aximum length 3ate
7alidation -mail Address validation and more. These are reusable and used in validation.xml. To define the form
specific validations. The validation.xml defines the validations applied to a form bean.
Q) What is +iles?
") Tiles is a framewor' for the development user interface Tiles is enables the developers to develop the web
applications by assembling the reusable tiles.
>. Add the Tiles Tag @ibrary 3escriptor (T@3) file to the web.xml.
9. 2reate layout JSPs.
<. 3evelop the web pages using layouts.
Q) <ow to call e&b from (trts?
>euse the Service @ocator patter to loo' up the e(bs.
9e&r you can use $nitial2ontext and get the home interface.
Q) What are the varios (trts ta$ libraries?
(trts.html ta$ library /# used for creating dynamic 1T)@ user interfaces and forms.
(trts.bean ta$ library /# provides substantial enhancements to the basic capability provided by .
(trts.lo$ic ta$ library /# can manage conditional generation of output text looping over ob(ect collections for
repetitive generation of output text and application flow management.
(trts.template ta$ library /# contains tags that are useful in creating dynamic JSP templates for pages which share a
common format.
(trts.tiles ta$ library /# This will allow you to define layouts and reuse those layouts with in our site.
(trts.nested ta$ library /#
Q) <ow yo will handle errors % e9ceptions sin$ (trts?
/To handle 5errors6 server side validation can be used using Action-rrors classes can be used.
/The 5e9ceptions6 can be wrapped across different layers to show a user showable exception.
/ Rsing validators
Q) What are the core classes of strts?
A) ActionAorm Action Action)apping ActionAorward etc.
Q) <ow yo will save the data across different pa$es for a particlar client reFest sin$ (trts?
A) $f the re*uest has a Aorm ob(ect the data may be passed on through the Aorm ob(ect across pages. &r within the
Action class call re*uest.getSession and use session.setAttribute() though that will persist through the life of the
session until altered.
!Or) 2reate an appropriate instance of ActionAorm that is form bean and store that form bean in session scope. So that
it is available to all the pages that for a part of the re*uest
Q) <ow wold strts handle :messa$es; reFired for the application?
A) )essages are defined in a 5.properties6 file as name value pairs. To ma'e these messages available to the
application 8ou need to place the .properties file in ,-C/$0A%classes folder and define in struts/config.xml
"message/resource parameterQ6title.empname6%#
and in order to display a message in a (sp would use this
"bean.message 'eyQ6title.empname6%#
Q) What is the difference between "ction=orm and #yna"ction=orm?
A) >. $n struts >.? action form is used to populate the html tags in (sp using struts custom tag.when the (ava code
changes the change in action class is needed. To avoid the chages in struts >.> dyna action form is introduced.This can
be used to develop using xml. The dyna action form bloats up with the struts/config.xml based definetion.
9. There is no need to write actionform class for the 3ynaActionAorm and all the variables related to the actionform
class will be specified in the struts/config.xml. ,here as we have to create Actionform class with getter and setter
methods which are to be populated from the form
<.if the formbean is a subclass of ActionAorm we can provide reset()validate()setters(to hold the values)gettters
whereas if the formbean is a subclass to 3ynaActionAorm we need not provide setters getters but in struts/config.xml
we have to configure the properties in using .basically this simplifies coding
3ynaActionAorm which allows you to configure the bean in the struts/config.xml file. ,e are going to use a subclass of
3ynaActionAorm called a 3yna7alidatorAorm which provides greater functionality when used with the validation framework.
"struts/config#
"form/beans#
"form/bean nameQKemployeeAormK typeQKorg.apache.struts.validator.3yna7alidatorAormK#
"form/property nameQKnameK typeQK(ava.lang.StringK%#
"form/property nameQKageK typeQK(ava.lang.StringK%#
"form/property nameQKdepartmentK typeQK(ava.lang.StringK initialQK9K %#
"form/property nameQKflavor$3sK typeQK(ava.lang.StringOPK%#
"form/property nameQKmethodTo2allK typeQK(ava.lang.StringK%#
"%form/bean#
"%form/beans#
"%struts/config#
This 3yna7alidatorAorm is used (ust li'e a normal ActionAorm when it comes to how we define its use in our action
mappings. The only Jtric'yJ thing is that standard getter and setters are not made since the 3ynaActionAorms are
bac'ed by a 1ash)ap. $n order to get fields out of the 3ynaActionAorm you would do.
String age Q (String)formCean.get(KageK)M
Similarly if you need to define a property.
formCean.set(KageKK<<K)M
Q) (trts how many :Controllers; can we have?
") 8ou can have multiple controllers but usually only one is needed
Q) Can I have more than one strts.confi$*9ml?
A) 8es you can $ have more than one.
"servlet#
"servlet/name#action"%servlet/name#
"servlet/class#org.apache.struts.action.ActionServlet"%servlet/class#
"init/param#
"param/name#config"%param/name#
"param/value#%,-C/$0A%struts/config.xml"%param/value#
"%init/param#
"W \ module configurations // #
"init/param#
"param/name#config%exercise"%param/name#
"param/value#%,-C/$0A%exercise%struts/config.xml"%param/value#
"%init/param#
"%servlet#
Q) Can yo write yor own methods in "ction class other than e9ecte!) and call the ser method directly?
") 8es we can create any number of methods in Action class and instruct the action tag in struts/config.xml file to call
that user methods.
Public class StudentAction extends 3ispatchAction
L
public ActionAorward read(Action)apping mapping ActionAorm form
1ttpServletHe*uest re*uest 1ttpServletHesponse response) throws -xceptio
L
Heturn some thingM
N
public ActionAorward update(Action)apping mapping ActionAorm form
1ttpServletHe*uest re*uest 1ttpServletHesponse response) throws -xceptio
L
Heturn some thingM
N
$f the user want to call any methods he would do something in struts/config.xml file.
"action pathQK%somepageK
typeQKcom.odccom.struts.action.StudentActionK
nameQKStudentAormK
"b#parameterQ6methodTo2all6"%b#
scopeQKre*uestK
validateQKtrueK#
"forward nameQKsuccessK pathQK%1ome.(spK %#
"%action#
Q) (trts.confi$*9ml
"struts/config#
"data/sources#
"data/source#
"set/property propertyQ6'ey6 valueQ66 urlQ66 maxcountQ66 mincountQ66 userQ66 pwdQ66 #
"%data/source#
"data/sources#
BKP describe the instance of the form bean.. C
"form/beans#
"form/bean nameQKemployee=ormK typeQKnet.reumann.-mployeeAormK%#
"%form/beans#

BKP to identify the tar$et of an action class when it retrns reslts .. C
"global/forwards#
"forward nameQKerrorK pathQK%error.(spK%#
"%global/forwards#
BKP describe an action instance to the action servlet.. C
"action/mappings#
"action pathQK%setRp-mployeeAormK typeQKnet.reumann.SetRp-mployeeActionK
nameQKemployee=ormK scopeQKre*uestK validateQKfalseK#
"forward nameQKcontinueK pathQK%employeeAorm.(spK%#
"%action#
"action pathQK%insert-mployeeK typeQKnet.reumann.$nsert-mployeeActionK
nameQKemployeeAormK scopeQKre*uestK validateQKtrueK
inputQK%employeeAorm.(spK#
"forward nameQKsuccessK pathQK%confirmation.(spK%#
"%action#
"%action/mappings#

"W\ to modify the default behaviour of the struts controller// #
"controller processor2lassQ66 bufferSi!eQ6 6 contentTypeQ66 no2acheQ66 maxAileSi!eQ66%#

BKP messa$e resorce properties .. C
"message/resources parameterQKApplicationHesourcesK nullQKfalseK %#
BKP/alidator pl$in
5plug/in class0ameQKorg.apache.struts.validator.7alidatorPlug$nK#
"set/property propertyQKpathnamesK valueQK%,-C/$0A%validator/rules.xml %,-C/$0A%validation.xmlK%#
"%plug/in#
BKP+iles pl$in
5plug/in class0ameQKorg.apache.struts.tiles.TilesPlug$nK#
"set/property propertyQKdefinitions/configK valueQK%,-C/$0A%tiles/defs.xml K%#
"%plug/in#
"%struts/config#
Q) Web*9ml> . .s a configuration file descri6e the deplo4ment elements.
"web/app#
"servlet#
"servlet/name#action"%servlet/name#
"servlet/class#org.apache.struts.action.ActionServlet"%servlet/class#

BKP1esorce Properties ..C
"init/param#
"param/name#application"%param/name#
"param/value#ApplicationHesources"%param/value#
"%init/param#

"init/param#
"param/name#config"%param/name#
"param/value#%,-C/$0A%struts/config.xml"%param/value#
"%init/param#
"load/on/startup#>"%load/on/startup#
"%servlet#
BK.. "ction (ervlet 'appin$ ..C
"servlet/mapping#
"servlet/name#action"%servlet/name#
"url/pattern#%do%X"%url/pattern#
"%servlet/mapping#
BK.. +he Welcome =ile Dist ..C
"welcome/file/list#
"welcome/file#index.(sp"%welcome/file#
"%welcome/file/list#
BK.. ta$ libs ..C
"taglib#
"taglib/uri#struts%bean/el"%taglib/uri#
"taglib/location#%,-C/$0A%struts/bean/el.tld"%taglib/location#
"%taglib#
"taglib#
"taglib/uri#struts%html/el"%taglib/uri#
"taglib/location#%,-C/$0A%struts/html/el.tld"%taglib/location#
"%taglib#

BKP+iles ta$ libs ..C
"taglib#
"taglib/uri#%tags%struts/tiles"%taglib/uri#
"taglib/location#%,-C/$0A%struts/tiles.tld"%taglib/location#
"%taglib#
BKP7sin$ =ilters ..C
"filter#
"filter/name#1ello,orldAilter"%filter/name#
"filter/class#1ello,orldAilter"%filter/class#
"%filter#
"filter/mapping#
"filter/name#1ello,orldAilter"%filter/name#
"url/pattern#HesponseServlet"% url/pattern #
"%filter/mapping#
"%web/app#
#atabase Qestions
Q) #'D insert update delete
##D create alter drop truncate rename.
#QD select
#CD grant revo'e.
+CD commit rollbac' savepoint.

Q) -ormali6ation
0ormali!ation is the process of simplifying the relationship between data elements in a record.
!i) ?
st
normal form> . >
st
0.A is achieved when all repeating groups are removed and P.I should be defined. big table is
bro'en into many small tables such that each table has a primary 'ey.
!ii) @
nd
normal form> . -liminate any non/full dependence of data item on record 'eys. $.e. The columns in a table which
is not completely dependant on the primary 'ey are ta'en to a separate table.
!iii) A
rd
normal form> . -liminate any transitive dependence of data items on P.IGs. i.e. Hemoves Transitive dependency.
$e $f ` is the primary 'ey in a table. 8 T d are columns in the same table. Suppose d depends only on 8 and 8 depends
on `. Then d does not depend directly on primary 'ey. So remove d from the table to a loo' up table.
Q) #iff Primary )ey and a 7niFe )ey? What is forei$n )ey?
") Coth primary 'ey and uni*ue enforce uni*ueness of the column on which they are defined. Cut by default primary
'ey creates a clustered index on the column where are uni*ue creates a nonclustered index by default. Another ma(or
difference is that primary 'ey doesnJt allow 0R@@s but uni*ue 'ey allows one 0R@@ only.
=orei$n )ey constraint prevents any actions that would destroy lin' between tables with the corresponding data values.
A foreign 'ey in one table points to a primary 'ey in another table. Aoreign 'eys prevent actions that would leave rows
with foreign 'ey values when there are no primary 'eys with that value. The foreign 'ey constraints are used to enforce
referential integrity.
21-2I constraint is used to limit the values that can be placed in a column. The chec' constraints are used to enforce
domain integrity.
0&T 0R@@ constraint enforces that the column will not accept null values. The not null constraints are used to enforce
domain integrity as the chec' constraints.
Q) #iff #elete % +rncate?
") Hollbac' is possible after 3-@-T- but THR02AT- remove the table permanently and canGt rollbac'. Truncate will
remove the data permanently we cannot rollbac' the deleted data.
#roppin$ > (Table structure S 3ata are deleted) $nvalidates the dependent ob(ects 3rops the indexes
+rncatin$ > (3ata alone deleted) Performs an automatic commit Aaster than delete
#elete > (3ata alone deleted) 3oesnGt perform automatic commit
Q) #iff /archar and /archar@?
") The difference between 7archar and 7archar9 is both are variable length but only 9??? bytes of character of data can
be store in varchar where as U??? bytes of character of data can be store in varchar9.
Q) #iff DO-8 % DO-8 1"W?
") 8ou use the @&04 datatype to store variable/length character strings. The @&04 datatype is li'e the 7AH21AH9
datatype except that the maximum length of a @&04 value is <9D;? bytes.
8ou use the @&04 HA, datatype to store binary data (or) byte strings. @&04 HA, data is li'e @&04 data except
that @&04 HA, data is not interpreted by P@%SY@. The maximum length of a @&04 HA, value is <9D;? bytes.
Q) #iff =nction % Procedre
Aunction is a self/contained program segment function will return a value but procedure not.
Procedure is sub program will perform some specific actions.
Q) <ow to find ot dplicate rows % delete dplicate rows in a table?
") )P$3 -)P0A)- -)PSS0
///// ////////// ///////////
> Jac' BBB/BB/BBBB
9 )i'e BBB/B^/BBBB
< Jac' BBB/BB/BBBB
U )i'e BBB/B^/BBBB
SY@# select count (empssn) empssn from employee group by empssn
having count (empssn) # >M
2&R0T (-)PSS0) -)PSS0
///////////// ///////////
9 BBB/BB/BBBB
9 BBB/B^/BBBB
SY@# delete from employee where (empid empssn)
not in (select min (empid) empssn from employee group by empssn)M
Q) (elect the nth hi$hest ran) from the table?
") Select X from tab t> where 9Q(select count (distinct (t9.sal)) from tab t9 where t>.sal"Qt9.sal)
Q) a) -mp table where fields emp0ame emp$d address
b) Salary table where fields -mp$d month Amount
these 9 tables he wants -mp$d emp0ame and salary for month 0ovember+
") Select emp.emp$d emp0ame Amount from emp salary where emp.emp$dQsalary.emp$d and monthQ0ovemberM
Q) OracleIPD(QD> (ynonyms?
") A synonym is an alternative name for ob(ects such as tables views se*uences stored procedures and other
database ob(ects
Syntax. /
2reate Oor replaceP OpublicP synonym Oschema.P synonymcname for Oschema.P ob(ectcnameM
or replace // allows you to recreate the synonym (if it already exists) without having to issue a 3H&P synonym
command.
Public // means that the synonym is a public synonym and is accessible to all users.
Schema // is the appropriate schema. $f this phrase is omitted &racle assumes that you are referring to your own
schema.
ob(ectcname // is the name of the ob(ect for which you are creating the synonym. $t can be one of the following.
Table Pac'age
7iew materiali!ed view
se*uence (ava class schema ob(ect
stored procedure user/defined ob(ect
Aunction Synonym

example.
2reate public synonym suppliers for app. suppliersM
-xample demonstrates how to create a synonym called suppliers. 0ow users of other schemas can reference the table
called suppliers without having to prefix the table name with the schema named app. Aor example.
Select X from suppliersM
$f this synonym already existed and you wanted to redefine it you could always use the or replace phrase as follows.
2reate or replace public synonym suppliers for app. suppliersM
3ropping a synonym
$t is also possible to drop a synonym.
drop OpublicP synonym Oschema .P Synonymcname OforcePM
public // phrase allows you to drop a public synonym. $f you have specified public then you donJt specify a schema.
Aorce // phrase will force &racle to drop the synonym even if it has dependencies. $t is probably not a good idea to use
the force phrase as it can cause invalidation of &racle ob(ects.

-xample.
3rop public synonym suppliersM
This drop statement would drop the synonym called suppliers that we defined earlier.
Q) What is an alias and how does it differ from a synonym?
") An alias is an alternative to a synonym designed for a distributed environment to avoid having to use the location
*ualifier of a table or view. The alias is not dropped when the table is dropped.
Q) What are &oins? Inner &oin % oter &oin?
") Cy using (oins you can retrieve data from two or more tables based on logical relationships between the tables
Inner Join> . returns all rows from both tables where there is a match.
Oter Join> . outer (oin includes rows from tables when there are no matching values in the tables.
_ @-AT J&$0 or @-AT &RT-H J&$0
The result set of a left outer (oin includes all the rows from the left table specified in the @-AT &RT-H clause not (ust
the ones in which the (oined columns match. ,hen a row in the left table has no matching rows in the right table the
associated result set row contains null values for all select list columns coming from the right table.
_ H$41T J&$0 or H$41T &RT-H J&$0.
A right outer (oin is the reverse of a left outer (oin. All rows from the right table are returned. 0ull values are returned for
the left table any time a right table row has no matching row in the left table.
_ AR@@ J&$0 or AR@@ &RT-H J&$0.
A full outer (oin returns all rows in both the left and right tables. Any time a row has no match in the other table the
select list columns from the other table contain null values. ,hen there is a match between the tables the entire result
set row contains data values from the base tables.
Q* #iff &oin and a 7nion?
") A (oin selects columns from 9 or more tables. A union selects rows.
when using the R0$&0 command all selected columns need to be of the same data type. The R0$&0 command
eliminate duplicate values.
Q* 7nion % 7nion "ll?
") The R0$&0 A@@ command is e*ual to the R0$&0 command except that R0$&0 A@@ selects all values. $t cannot
eliminate duplicate values.
# S-@-2T -c0ame AH&) -mployeesc0orway
R0$&0 A@@
S-@-2T -c0ame AH&) -mployeescRSA
Q) Is the forei$n )ey is niFe in the primary table?
") 0ot necessary
Q) +able mentioned below named employee
$3 0A)- )$3
> 2-& 0ull
9 7P 2-&
< 3irector 7P
As'ed to write a *uery to obtain the following output
2-& 0ull
7P 2-&
3irector 7P
") SY@# Select a.name b.name from employee a employee b where a.midQb.id(S).
Q) E9plain a scenario when yo donQt $o for normali6ation?
") $f we r sure that there wont be much data redundancy then donGt go for normali!ation.
Q) What is 1eferential inte$rity?
") H.$ refers to the consistency that must be maintained between primary and foreign 'eys i.e. every foreign 'ey value
must have a corresponding primary 'ey value.
Q) What techniFes are sed to retrieve data from more than one table in a sin$le (QD statement?
") Joins unions and nested selects are used to retrieve data.
Q) What is a view? Why se it?
") A view is a virtual table made up of data from base tables and other views but not stored separately.
Q) S-@-2T statement syntax+
") S-@-2T O 3$ST$02T ] A@@ P columncexpression> columncexpression9 ....
O AH&) fromcclause P
O ,1-H- wherecexpression P
O 4H&RP C8 expression> expression9 .... P
O 1A7$04 havingcexpression P
O &H3-H C8 orderccolumncexpr> orderccolumncexpr9 .... P
columncexpression ..Q expression O AS P O columncalias P
fromcclause ..Q selectctable> selectctable9 ...
fromcclause ..Q selectctable> @-AT O&RT-HP J&$0 selectctable9 &0 expr ...
fromcclause ..Q selectctable> H$41T O&RT-HP J&$0 selectctable9 &0 expr ...
fromcclause ..Q selectctable> O$00-HP J&$0 selectctable9 ...
selectctable ..Q tablecname O AS P O tablecalias P
selectctable ..Q ( subcselectcstatement ) O AS P O tablecalias P
orderccolumncexpr ..Q expression O AS2 ] 3-S2 P
Q) #I(+I-C+ clase?
") The 3$ST$02T clause allows you to remove duplicates from the result set.
# S-@-2T 3$ST$02T city AH&) supplierM
Q) CO7-+ fnction?
") The 2&R0T function returns the number of rows in a *uery
# S-@-2T 2&R0T (X) as K0o of empsK AH&) employees ,1-H- salary # 9B???M
Q) #iff <"/I-8 CD"7(E % W<E1E CD"7(E?
") 1aving 2lause is basically used only with the 4H&RP C8 function in a *uery. ,1-H- 2lause is applied to each row
before they are part of the 4H&RP C8 function in a *uery.
Q) #iff 81O7P 0V % O1#E1 0V?
") 4roup by controls the presentation of the rows order by controls the presentation of the columns for the results of
the S-@-2T statement.
# S-@-2T Kcolcnam>K SR)(Kcolcnam9K) AH&) KtabcnameK 4H&RP C8 Kcolcnam>K
# S-@-2T KcolcnamK AH&) KtabcnamK O,1-H- KconditionKP &H3-H C8 KcolcnamK OAS2 3-S2P
Q) What )eyword does an (QD (EDEC+ statement se for a strin$ search?
") The @$I- 'eyword allows for string searches. The Z sign is used as a wildcard.
Q) What is a -7DD vale? What are the pros and cons of sin$ -7DD(?
") 0R@@ value ta'es up one byte of storage and indicates that a value is not present as opposed to a space or !ero
value. A 0R@@ in a column means no entry has been made in that column. A data value for the column is Kun'nownK or
Knot available.K
Q) Inde9? +ypes of inde9es?
") @ocate rows more *uic'ly and efficiently. $t is possible to create an index on one (or) more columns of a table and
each index is given a name. The users cannot see the indexes they are (ust used to speed up *ueries.
Rni*ue $ndex . /
A uni*ue index means that two rows cannot have the same index value.
#2H-AT- R0$YR- $03-` indexcname &0 tablecname (columncname)
,hen the R0$YR- 'eyword is omitted duplicate values are allowed. $f you want to index the values in a column in
descending order you can add the reserved word 3-S2 after the column name.
#2H-AT- $03-` Person$ndex &0 Person (@ast0ame 3-S2)

$f you want to index more than one column you can list the column names within the parentheses.
#2H-AT- $03-` Person$ndex &0 Person (@ast0ame Airst0ame)
Q) #iff sbFeries % Correlated sbFeries?
")sub5ueries are sel"2contained. 0one of them have used a reference from outside the sub*uery.
correlated sub5uery cannot be evaluated as an independent *uery but can reference columns in a table listed in the
from list of the outer *uery.
Q) Predicates I-5 "-V5 "DD5 EJI(+(?
") Sub *uery can return a subset of !ero to n values. According to the conditions which one wants to express one can
use the predicates $0 A08 A@@ or -`$STS.
$0 The comparison operator is the e*uality and the logical operation between values is &H.
A08 Allows to chec' if at least a value of the list satisfies condition.
A@@ Allows to chec' if condition is reali!ed for all the values of the list.
-`$STS $f the sub*uery returns a result the value returned is True otherwise the value returned is Aalse.
Q) What are some sFl "$$re$ates and other 0ilt.in fnctions?
") A74 SR) )$0 )A` 2&R0T and 3$ST$02T.
#esi$n Patterns Qestions
J@EE #esi$n Patterns
Q) What is a #esin Pattern? Why se patterns?
A) A pattern describes a proven solution to a recurring design problem* Patterns provide a ready/made solution that can
be adapted to different problems as necessary.
Q) J@EE #esi$n Patterns?
#ispatcher /iew. 2ombines a 3ispatcher component with the Aront 2ontroller and 7iew 1elper patterns deferring
many activities to 7iew processing.
(ervice to Wor)er. 2ombines a 3ispatcher component with the Aront 2ontroller and 7iew 1elper patterns.
+ransfer Ob&ect "ssembler> $t is used to build the re*uired model or submodel. The Transfer &b(ect Assembler uses
Transfer &b(ects to retrieve data from various business ob(ects and other ob(ects that define the model or part of the
model.
Composite Entity .$t model represent and manage a set of interrelated persistent ob(ects rather than representing
them as individual fine/grained entity beans. A 2omposite -ntity bean represents a graph of ob(ects.
(ervice "ctivator Service Activator enables asynchronous access to enterprise beans and other business services. $t
receives asynchronous client re*uests and messages. &n receiving a message the Service Activator locates and
invo'es the necessary business methods on the business service components to fulfill the re*uest asynchronously. $n
-JC9.? )essage 3riven beans can be used to implement Service Activator for message based enterprise applications.
The Service Activator is a J)S @istener and delegation service that creates a message fagade for the -JCs.
Q) What is architectral desi$n pattern?
") 3escribe )729 T Aront 2ontroller.
=ront Controller
$t will dispatch the re*uest to the correct resource 2entrali!ed controller for managing and holding of a re*uest.
(ervice Docator
To access different resources%services J9-- compatible server binds these resources%services to the J03$
server so that the clients can loo'up those resources%services through J03$ loo'up process from anywhere in the
networ'. The resources%services can be
Tier Pattern 0ame
+ $ntercepting Ailter
+ Aront 2ontroller
+ 7iew 1elper
+ 2omposite view
+ Service to ,or'er
+ 3ispacther 7iew
+ Cusiness 3elegate
+ 7alue &b(ect
+ Session Aagade
+ 2omposite -ntity
+ 7alue &b(ect Assembler
+ 7alue @ist 1andler
+ Service @ocator
+ 3ata Access &b(ect
+ Service Activator
Presentation Tier
Cusiness Tier
$ntegration Tier
>. -JC1ome ob(ects 9. 3ataSource ob(ects <. J)S 2onnectionAactory U. J)S Topic%Yueue etc.
All these services need to bind to the J03$ services and the clients need to loo'up J03$ to get those services. 2lients
have to go through J03$ loo'up process every time to wor' with these services. J03$ loo'up process is expensive
because clients need to get networ' connection to the J03$ server if the J03$ server is located on a different machine
and need to go through loo'up process every time this is redundant and expensive.
The solution for the redundant and expensive J03$ loo'up process problem is to cache those service ob(ects
when the client performs J03$ loo'up first time and reuse that service ob(ect from the cache second time onwards for
other clients. This techni*ue maintains a cache of service ob(ects and loo's up the J03$ only first time for a service
ob(ect.
(ession =aXade
-JC clients (swing servlets (sps etc) can access entity beans directly. $f -JC clients access entity beans
directly over the networ' it ta'es more networ' calls and imposes networ' overhead.
1ere the servlet calls multiple entity beans directly to accomplish a business process thereby increasing the number of
networ' calls.
The solution for avoiding number of networ' calls due to directly accessing multiple entity beans is to wrap
entity beans with session bean (Aacade). The -JC client accesses session bean (Aacade) instead of entity beans
through coarse grained method call to accomplish a business process.
'essa$e =acade
Session bean and entity bean methods execute synchronously that means the method caller has to wait till a
value is returned. $n some situations li'e sending hundredJs of mails or firing a batch process or updating processes the
client does not have to bother about return value. $f you use synchronous session and entity beans in such situations
they ta'e a long time to process methods and clients have to wait till the method returns a value.
The client has to wait till all the eight synchronous steps complete. This synchronous execution ta'es a long time and
has an impact on performance when the method process is huge.
To avoid bloc'ing of a client use asynchronous message driven beans so that client does not have to wait for a
return value. $f a client uses asynchronous messaging then the client need not wait for a return value but can continue
its flow of execution after sending the message.
/ale Ob&ect !#+O.#ata+ransfer Ob&ect)
,hen a client calls a remote method there will be process of marshalling networ' calls and unmarshalling
involved for the remote method invocation. $f you choose fine/grained approach when calling methods remotely there
will be a significant networ' overhead involved. Aor example if you call fine grained method li'e this
remote&b(ect.get0ame()M
remote&b(ect.get2ity()M
remote&b(ect.getState()M
there are three networ' calls from client to the remote ob(ect because every method call is remote method call.
The solution for avoiding many networ' calls due to fine/grained method calls is to use coarse/grained approach. Aor
example.
%% 2reate a 7alue &b(ect and fill that ob(ect locally
Person$nfo person Q new Person$nfo()M
person.set0ame(KHaviK)M
person.set2ity(KAustinK)M
%% send 7alue &b(ect through networ'
remote&b(ect.getPerson$nfo(person)M
1ere there is only one networ' call instead of three networ' calls and Person$nfo ob(ect is a 7alue &b(ect. The following
figure illustrates the coarse grained approach that is passing a 7alue &b(ect through networ'.
7alue &b(ect is an ob(ect that is passed over the networ' rather than passing each attributes separately thus increasing
performance by reducing networ' calls.
/aleOb&ect=actory
Aor a sin$le reFest a client might need to access mltiple server side components such as different
session beans and entity beans. $n such situations the client accesses multiple components over the networ' this
increases the networ' traffic and has an impact on the performance.

To reduce the networ' traffic due to accessing multiple components by a client for a single re*uest let
7alue&b(ectAactory hold different 7alue&b(ects as placeholders and respond with a single 7alue&b(ect for a client
re*uest.
/ale Dist <andler !#"O)
J9-- applications generally have the search facility and have to search huge data and retrieve results. $f an
application returns huge *ueried data to the client the client ta'es long time to retrieve that large data and $f that
application uses entity bean to search data it has an impact on.

>. Rse 3ata Access &b(ects (3A&) rather than -ntity beans
9. Heturn small *uantity of data multiple times iteratively rather than returning large amount of data at once to the client.
3A& encapsulates J3C2 access logic. 7alue@ist1andler caches list of 7alue ob(ects that are retrieved through 3A&.
,hen client wants to search data $t calls 7alue@ist1andler that is in turn responsible for caching data and returning data
to the client iteratively.

(in$leton
8ou can achieve this by having the private constructor in the class so that other classes canJt create a new instance.
$ts intent is to ensure that a class has only one instance and to provide a global point of access to it. There are many
situations in which a singleton ob(ect is necessary. a 4R$ application must have a single mouse an active modem
needs one and only one telephone line an operating system can only have one window manager and a P2 is
connected to a single 'eyboard
>.2reate a Private constructor so that outside class can not access this constructor. And declare a private static
reference of same class.
9. ,rite a public Aactory method which creates an ob(ect. Assign this ob(ect to private static Heference and return
the ob(ect
public class Singleton
L
private static Singleton refM
private Singleton ()L
N
public static Singleton getSingleton()
L
if (ref QQ null)
ref Q new Singleton ()M
return refM
N
N
0siness #ele$ate
The C.3 acts as a client/side business abstraction and hides the implementation of the business services. such
as loo)p % access details of the EJ0 architectre.
The delegate may cache results and references to remote business services. 2aching can significantly improve
performance because it limits unnecessary and potentially costly round trips over the networ'.
C.3 uses a component called the Doo)p (ervice. The @oo'up Service is responsible for hiding the underlying
implementation details of the business service loo'up code.
The client re*uests the Cusiness3elegate to provide access to the underlying business service. The Cusiness3elegate
uses a @oo'upService to locate the re*uired CusinessService component.
Q)* Where do yo se sin$leton pattern and why?
A) $f $ re*uire a single instance of an ob(ect in a particular J7) ex while designing database connection pool. $ would
re*uire a single connection ob(ect for all the users coming in not a separate one for each user.
Q)* Why =actory Pattern is sed and an e9ample?
A) Aactory pattern is used in place where the implementation varies over time. Aactory pattern suggest creating many
different instances from interfaces. $nterfaces are the one that faces client and implementation of those methods come
from factory depending on a specific condition.
ex. $f the &S is ,indows loo' and feel of the application changes to ,indow style for @inux it is )etal and for
machintosh it will be different.

Q)* Where do yo se visitor pattern and why?
A) $f $ want to defrag business logic in different sets of modules and the final processing re*uires all these module to be
included in a particular fashion. 7isitor pattern generally calls a visit method of these modules %ob(ects and
all the different logic stored in different modules and call one by one. $t is something li'e visiting many modules one at a
time.

Q)* What problem an observer pattern solves?
A) $f a particular event has to be notified to many ob(ects and list grows over time and it is hardly possible to call %notify
each and every listeners at design time. ,e use observer pattern (ust to register many ob(ects listening to a particular
event and getting notified automatically as and when the event occurs.

Q) What is the difference between J@EE desi$n patterns and the 8an$ of =or patterns?
A) The 4&A design patterns apply generically to any ob(ect/oriented programming language. J9-- design patterns
address common problems encountered in designing J9-- architecture. This course presents the 'ey J9-- design
patterns re*uired when implementing a J9-- system.
(ecrity Qestions
Q) Java (ecrity 'odel
0yte code verifier
,hich examine the byte code of a class before executing. The verifier chec's that the instructions cannot
perform actions that are obviously damaging.
ClassDoader
2lass@oader which restrict access to the classes which can be loaded into J7) 2lass@oader 'eeps the record
of classes which can be loaded into J7).
(ecrity mana$er
Hestrict access to potentially dangerous operations. S.) provides a sand box in which applet run. 8ou can also
define a set of sand boxes applying a different san box to each program. S.) is a class that controls weather a specific
operation are permitted S.) will perform operations li'e opening 0., soc'et creating S.) perform 0., multi cast
etce
Q) 0asic "thentication % #i$est "thentication
0asic "thentication $s a security model in this the client must authenticate itself with user id and password for
each resource to access. $n this the user id and password are sent by the client in base/;U encoded
string the server decode the string and loo's in the data base for match. $f it finds a match grant access
to the re*uested resource.
#i$est "thentication $n this the user id and password does not send across the networ' instead send a digest
representation of password.

S-ar putea să vă placă și