You are on page 1of 233

Core java

Q1. What is the difference between an Abstract class and Interface?


1. Abstract classes may have some executable methods and methods left
unimplemented. Interfaces contain no implementation code.
2. An class can implement any number of interfaces, but subclass at most one abstract class.
3. An abstract class can have nonabstract methods. All methods of an interface are
abstract.
4. An abstract class can have instance variables. An interface cannot.
5. An abstract class can define constructor. An interface cannot.
6. An abstract class can have any visibility public, protected, private or none
!pac"a#e$. An interface%s visibility must be public or none !pac"a#e$.
&. An abstract class inherits from 'b(ect and includes methods such as clone!$ and
e)uals!$.
Q2.What are checked and unchecked exceptions?
*ava defines t+o "inds of exceptions
, Checked exceptions -xceptions that inherit from the !xception class are
checked exceptions. .lient code has to handle the chec"ed exceptions thro+n by
the A/I, either in a catch clause or by for+ardin# it out+ard +ith the thro+s clause.
-xamples 0 "Q#!xception$ I%xception.
, &nchecked exceptions 1untime-xception also extends from -xception. 2o+ever,
all of the exceptions that inherit from 1untime-xception #et special treatment.
3here is no re)uirement for the client code to deal +ith them, and hence they are
called unchec"ed exceptions. -xample 4nchec"ed exceptions are
'ull(ointer!xception$ %ut%f)e*or+!rror$ ,ivide-+.ero!xception t+picall+$
pro/ra**in/ errors.
Q0.What is a user defined exception?
4ser0defined exceptions may be implemented by
, definin# a class to respond to the exception and
, embeddin# a thro+ statement in the try bloc" +here the exception can occur or
declarin# that the method thro+s the exception !to another method +here it is
handled$.
3he developer can define a ne+ exception by derivin# it from the -xception class as follo+s
public class 5y-xception extends -xception 6
78 class definition of constructors !but 9'3 the exception handlin# code$ #oes here public
5y-xception!$ 6
super!$:
;
public 5y-xception! <trin# error5essa#e $ 6
super! error5essa#e $:
;
;
3he thro+ statement is used to si#nal the occurance of the exception +ithin a try bloc". 'ften,
exceptions are instantiated in the same statement in +hich they are thro+n usin# the
syntax.
thro+ ne+ 5y-xception!=I thre+ my o+n exception.=$
3o handle the exception +ithin the method +here it is thro+n, a catch statement that handles
5y-xception, must follo+ the try bloc". If the developer does not +ant to handle the exception in the
method itself, the method must pass the exception usin# the syntax
public *+)ethod'a*e12 throws )+!xception
Q3.What is the difference between C44 5 6ava?
>ell as ?(arne <troustrup says =..despite the syntactic similarities, .@@ and *ava are very different
lan#ua#es. In many +ays, *ava seems closer to <malltal" than to .@@..=. 2ere are fe+ I discovered
, *ava is multithreaded
, *ava has no pointers
, *ava has automatic memory mana#ement !#arba#e collection$
, *ava is platform independent !<troustrup may differ by sayin# =*ava is a platform=
, *ava has built0in support for comment documentation
, *ava has no operator overloadin#
, *ava doesnAt provide multiple inheritance
, 3here are no destructors in *ava
Q7.What are state*ents in 6A8A ?
<tatements are e)uivalent to sentences in natural lan#ua#es. A statement forms a complete
unit of execution. 3he follo+in# types of expressions can be made into a statement by
terminatin# the expression +ith a semicolon
, Assi#nment expressions
, Any use of @@ or 00
, 5ethod calls
, 'b(ect creation expressions
3hese "inds of statements are called expression statements. In addition to these "inds of
expression statements, there are t+o other "inds of statements. A declaration statement
declares a variable. A control flo+ statement re#ulates the order in +hich statements #et
executed. 3he for loop and the if statement are both examples of control flo+ statements.
Q9.What is 6A: file?
*avaA1chive files are a bi# #lob of *ava classes, ima#es, audio, etc., compressed to ma"e
one simple, smaller file to ease Applet do+nloadin#. 9ormally +hen a bro+ser encounters
an applet, it #oes and do+nloads all the files, ima#es, audio, used by the Applet separately.
3his can lead to slo+er do+nloads.
Q;.What is 6'I?
*9I is an acronym of *ava 9ative Interface. 4sin# *9I +e can call functions +hich are +ritten in other
lan#ua#es from *ava. Bollo+in# are its advanta#es and disadvanta#es.
Advanta/es
, Cou +ant to use your existin# library +hich +as previously +ritten in other
lan#ua#e.
, Cou +ant to call >indo+s A/I function.
, Bor the sa"e of execution speed.
, Cou +ant to call A/I function of some server product +hich is in c or c@@ from (ava
client.
,isadvanta/es
, Cou canAt say +rite once run any+here.
, Difficult to debu# runtime error in native code.
, /otential security ris".
, Cou canAt call it from Applet.
Q<.What is seriali=ation?
Euite simply, ob(ect serialiFation provides a pro#ram the ability to read or +rite a +hole ob(ect to and
from a ra+ byte stream. It allo+s *ava ob(ects and primitives to be encoded into a byte stream
suitable for streamin# to some type of net+or" or to a file0system, or more #enerally, to a
transmission medium or stora#e facility. A seraliFable ob(ect must implement the <eriliFable interface.
>e use 'b(ect'utput<tream to +rite this ob(ect to a stream and 'b(ectInput<tream to read it from
the stream.
Q>.Wh+ there are so*e null interface in java ? What does it *ean ? ?ive *e so*e null
interfaces in 6A8A?
9ull interfaces act as mar"ers..they (ust tell the compiler that the ob(ects of this class need to
be treated differently..some mar"er interfaces are <erialiFable, 1emote, .loneable
Q1@. Is s+nchronised a *odifier?indentifier??what is it??
It%s a modifier. <ynchroniFed methods are methods that are used to control access to an ob(ect. A
thread only executes a synchroniFed method after it has ac)uired the loc" for the method%s ob(ect or
class. <ynchroniFed statements are similar to synchroniFed methods. A synchroniFed statement can
only be executed after a thread has ac)uired the loc" for the ob(ect or class referenced in the
synchroniFed statement.
Q11.What is sin/leton class?where is it used?
<in#leton is a desi#n pattern meant to provide one and only one instance of an ob(ect. 'ther ob(ects
can #et a reference to this instance throu#h a static method !class constructor is "ept private$. >hy
do +e need oneG <ometimes it is necessary, and often sufficient, to create a sin#le instance of a #iven
class. 3his has advanta#es in memory mana#ement, and for *ava, in #arba#e collection. 5oreover,
restrictin# the number of instances may be necessary or desirable for technolo#ical or business
reasons00for example, +e may only +ant a sin#le instance of a pool of database connections.
Q12.What is a co*pilation unit?
3he smallest unit of source code that can be compiled, i.e. a .(ava file.
Q10.Is strin/ a wrapper class?
<trin# is a class, but not a +rapper class. >rapper classes li"e !Inte#er$ exist for each primitive type.
3hey can be used to convert a primitive data value into an ob(ect, and viceversa.
Q13.Wh+ java does not have *ultiple inheritance?
3he *ava desi#n team strove to ma"e *ava
, <imple, ob(ect oriented, and familiar
, 1obust and secure
, Architecture neutral and portable
, 2i#h performance
, Interpreted, threaded, and dynamic
3he reasons for omittin# multiple inheritance from the *ava lan#ua#e mostly stem from the =simple,
ob(ect oriented, and familiar= #oal. As a simple lan#ua#e, *ava%s creators +anted a lan#ua#e that most
developers could #rasp +ithout extensive trainin#. 3o that end, they +or"ed to ma"e the lan#ua#e as
similar to .@@ as possible !familiar$ +ithout carryin# over .@@%s unnecessary complexity !simple$.
In the desi#ners% opinion, multiple inheritance causes more problems and confusion than it solves. <o
they cut multiple inheritance from the lan#ua#e !(ust as they cut operator overloadin#$. 3he desi#ners%
extensive .@@ experience tau#ht them that multiple inheritance (ust +asn%t +orth the headache.
Q17.Wh+ java is not a 1@@A oops?
5any people say this because *ava uses primitive types such as int, char, double. ?ut then all the rest
are ob(ects. .onfusin# )uestion.
Q19.What is a resource bundle?
In its simplest form, a resource bundle is represented by a text file containin# "eys and a text value
for each "ey.
Q1;.What is transient variable?
3ransient variable can%t be serialiFe. Bor example if a variable is declared as transient in a <erialiFable
class and the class is +ritten to an 'b(ect<tream, the value of the variable can%t be +ritten to the
stream instead +hen the class is retrieved from the 'b(ect<tream the value of the variable
becomes null.
Q1<.What is Collection A(I?
3he .ollection A/I is a set of classes and interfaces that support operation on collections of ob(ects.
3hese classes and interfaces are more flexible, more po+erful, and more re#ular than the vectors,
arrays, and hashtables if effectively replaces.
!xa*ple of classes 2ash<et, 2ash5ap, ArrayHist, Hin"edHist, 3ree<et and 3ree5ap.
!xa*ple of interfaces .ollection, <et, Hist and 5ap.
Q1>.Is Iterator a Class or Interface? What is its use?
Iterator is an interface +hich is used to step throu#h the elements of a .ollection.
Q2@.What is si*ilaritiesBdifference between an Abstract class and Interface?
,ifferences are as follows
, Interfaces provide a form of multiple inheritance. A class can extend only one other
class.
, Interfaces are limited to public methods and constants +ith no implementation.
Abstract classes can have a partial implementation, protected parts, static methods,
etc.
, A .lass may implement several interfaces. ?ut in case of abstract class, a class may extend only one
abstract class.
, Interfaces are slo+ as it re)uires extra indirection to to find correspondin# method
in in the actual class. Abstract classes are fast.
"i*ilarities
, 9either Abstract classes or Interface can be instantiated.
Q21.What is a transient variable?
A transient variable is a variable that may not be serialiFed.
Q22.Which containers use a border #a+out as their default la+out?
3he +indo+, Brame and Dialo# classes use a border layout as their default layout.
Q20.Wh+ do threads block on IB%?
3hreads bloc" on i7o !that is enters the +aitin# state$ so that other threads may execute +hile the i7o
'peration is performed.
Q23.Cow are %bserver and %bservable used?
'b(ects that subclass the 'bservable class maintain a list of observers. >hen an 'bservable ob(ect is
updated it invo"es the update!$ method of each of its observers to notify the observers that it has
chan#ed state. 3he 'bserver interface is implemented by ob(ects that observe 'bservable ob(ects.
Q21.What is a transient variable?
A transient variable is a variable that may not be serialiFed.
Q22.Which containers use a border #a+out as their default la+out?
3he +indo+, Brame and Dialo# classes use a border layout as their default layout.
Q20.Wh+ do threads block on IB%?
3hreads bloc" on i7o !that is enters the +aitin# state$ so that other threads may execute +hile the i7o
'peration is performed.
Q23.Cow are %bserver and %bservable used?
'b(ects that subclass the 'bservable class maintain a list of observers. >hen an 'bservable ob(ect is
updated it invo"es the update!$ method of each of its observers to notify the observers that it has
chan#ed state. 3he 'bserver interface is implemented by ob(ects that observe 'bservable ob(ects.
Q27.What is s+nchroni=ation and wh+ is it i*portant?
>ith respect to multithreadin#, synchroniFation is the capability to control the access of multiple
threads to shared resources. >ithout synchroniFation, it is possible for one thread to modify a shared
ob(ect +hile another thread is in the process of usin# or updatin# that ob(ect%s value. 3his often leads
to si#nificant errors.
Q29. Can a lock be acDuired on a class?
Ces, a loc" can be ac)uired on a class. 3his loc" is ac)uired on the class%s .lass ob(ect.
Q2;. WhatEs new with the stop12$ suspend12 and resu*e12 *ethods in 6,F 1.2?
3he stop!$, suspend!$ and resume!$ methods have been deprecated in *DI 1.2.
Q2<. Is null a ke+word?
3he null value is not a "ey+ord.
Q2>. What is the preferred si=e of a co*ponent?
3he preferred siFe of a component is the minimum component siFe that +ill allo+ the
component to display normally.
Q0@. What *ethod is used to specif+ a containerEs la+out?
3he setHayout!$ method is used to specify a container%s layout.
Q01. Which containers use a Glow#a+out as their default la+out?
3he /anel and Applet classes use the Blo+Hayout as their default layout.
Q02. What state does a thread enter when it ter*inates its processin/?
>hen a thread terminates its processin#, it enters the dead state.
Q00. What is the Collections A(I?
3he .ollections A/I is a set of classes and interfaces that support operations on collections of ob(ects.
Q03. Which characters *a+ be used as the second character
of an identifier$ but not as the first character of an identifier?
3he di#its J throu#h K may not be used as the first character of an identifier but they may be used
after the first character of anidentifier.
Q07. What is the #ist interface?
3he Hist interface provides support for ordered collections of ob(ects.
Q09. Cow does 6ava handle inte/er overflows and underflows?
It uses those lo+ order bytes of the result that can fit into the siFe of the type allo+ed by the
operation.
Q0;. What is the 8ector class?
3he Lector class provides the capability to implement a #ro+able array of ob(ects
Q0<. What *odifiers *a+ be used with an inner class that is a *e*ber of an outer class?
A !non0local$ inner class may be declared as public, protected, private, static, final, or abstract.
Q0>. What is an Iterator interface?
3he Iterator interface is used to step throu#h the elements of a .ollection.
Q3@. What is the difference between the HH and HHH operators?
3he MM operator carries the si#n bit +hen shiftin# ri#ht. 3he MMM Fero0fills bits that have been shifted
out.
Q31. Which *ethod of the Co*ponent class is used to set the position and si=e of a
co*ponent?
set?ounds!$
Q32. Cow *an+ bits are used to represent &nicode$ A"CII$ &IGJ19$ and &IGJ< characters?
4nicode re)uires 16 bits and A<.II re)uire & bits. Althou#h the A<.II character set uses only & bits, it
is usually represented as Nbits. 43B0N represents characters usin# N, 16, and 1N bit patterns. 43B016
uses 160bit and lar#er bit patterns.
Q30. What is the difference between +ieldin/ and sleepin/?
>hen a tas" invo"es its yield!$ method, it returns to the ready state. >hen a tas" invo"es its sleep!$
method, it returns to the +aitin# state.
Q33. Which java.util classes and interfaces support event handlin/?
3he -vent'b(ect class and the -ventHistener interface support event processin#.
Q37. Is si=eof a ke+word?
3he siFeof operator is not a "ey+ord.
Q39. What are wrapped classes?
>rapped classes are classes that allo+ primitive types to be accessed as ob(ects.
Q3;. ,oes /arba/e collection /uarantee that a pro/ra* will not run out of *e*or+?
Oarba#e collection does not #uarantee that a pro#ram +ill not run out of memory. It is possible for
pro#rams to use up memory resources faster than they are #arba#e collected. It is also possible for
pro#rams to create ob(ects that are not sub(ect to #arba#e collection
Q3<. What restrictions are placed on the location of a packa/e state*ent within a source
code file?
A pac"a#e statement must appear as the first line in a source code file !excludin# blan" lines and
comments$.
Q3>. Can an objectEs finali=e12 *ethod be invoked while it is reachable?
An ob(ect%s finaliFe!$ method cannot be invo"ed by the #arba#e collector +hile the ob(ect is still
reachable. 2o+ever, an ob(ect%s finaliFe!$ method may be invo"ed by other ob(ects.
Q7@. What is the i**ediate superclass of the Applet class?
/anel
Q71. What is the difference between pree*ptive schedulin/ and ti*e slicin/?
4nder preemptive schedulin#, the hi#hest priority tas" executes until it enters the +aitin# or
dead states or a hi#her priority tas" comes into existence. 4nder time slicin#, a tas" executes for a
predefined slice of time and then reenters the pool of ready tas"s. 3he scheduler then determines
+hich tas" should execute next, based on priority and other factors.
Q72 'a*e three Co*ponent subclasses that support paintin/.
3he .anvas, Brame, /anel, and Applet classes support paintin#.
Q70. What value does read#ine12 return when it has reached the end of a file?
3he readHine!$ method returns null +hen it has reached the end of a file.
Q73. What is the i**ediate superclass of the ,ialo/ class?
>indo+
Q77. What is clippin/?
.lippin# is the process of confinin# paint operations to a limited area or shape.
Q79. What is a native *ethod?
A native method is a method that is implemented in a lan#ua#e other than *ava.
Q7;. Can a for state*ent loop indefinitel+?
Ces, a for statement can loop indefinitely. Bor example, consider the follo+in# for!::$ :
Q7<. What are order of precedence and associativit+$ and how are the+ used?
'rder of precedence determines the order in +hich operators are evaluated in expressions. Associatity
determines +hether an expression is evaluated left0to0ri#ht or ri#ht0to0left
Q7>. When a thread blocks on IB%$ what state does it enter?
A thread enters the +aitin# state +hen it bloc"s on I7'.
Q9@. Io what value is a variable of the "trin/ t+pe auto*aticall+ initiali=ed?
3he default value of an <trin# type is null.
Q91. What is the catch or declare rule for *ethod declarations?
If a chec"ed exception may be thro+n +ithin the body of a method, the method must either catch the
exception or declare it in its thro+s clause.
Q92. What is the difference between a )enuIte* and a Checkbox)enuIte*?
3he .hec"box5enuItem class extends the 5enuItem class to support a menu item that may be
chec"ed or unchec"ed.
Q90. What is a taskEs priorit+ and how is it used in schedulin/?
A tas"%s priority is an inte#er value that identifies the relative order in +hich it should be executed
+ith respect to other tas"s. 3he scheduler attempts to schedule hi#her priority tas"s before lo+er
priority tas"s.
Q93. What class is the top of the AWI event hierarch+?
3he (ava.a+t.A>3-vent class is the hi#hest0level class in the A>3 event0class hierarchy.
Q97. When a thread is created and started$ what is its initial state?
A thread is in the ready state after it has been created and started.
Q99. Can an anon+*ous class be declared as i*ple*entin/ an interface and extendin/ a
class?
An anonymous class may implement an interface or extend a superclass, but may not be declared to
do both.
Q9;. What is the ran/e of the short t+pe?
3he ran#e of the short type is 0!2P15$ to 2P15 0 1.
Q9<. What is the ran/e of the char t+pe?
3he ran#e of the char type is J to 2P16 0 1.
Q9>. In which packa/e are *ost of the AWI events that support the eventJdele/ation
*odel defined?
5ost of the A>30related events of the event0dele#ation model are defined in the
(ava.a+t.event pac"a#e. 3he A>3-vent class is defined in the (ava.a+t pac"a#e.
Q;@. What is the i**ediate superclass of )enu?
5enuItem
Q;1. What is the purpose of finali=ation?
3he purpose of finaliFation is to #ive an unreachable ob(ect the opportunity to perform any cleanup
processin# before the ob(ect is #arba#e collected.
Q;2. Which class is the i**ediate superclass of the )enuCo*ponent class.
'b(ect
Q;0. What invokes a threadEs run12 *ethod?
After a thread is started, via its start!$ method or that of the 3hread class, the *L5 invo"es the
thread%s run!$ method +hen the thread is initially executed.
Q;3. What is the difference between the -oolean 5 operator and the 55 operator?
If an expression involvin# the ?oolean Q operator is evaluated, both operands are
evaluated. 3hen the Q operator is applied to the operand. >hen an expression involvin# the QQ
operator is evaluated, the first operand is evaluated. If the first operand returns a value of true then
the second operand is evaluated. 3he QQ operator is then applied to the first and second operands. If
the first operand evaluates to false, the evaluation of the second operand is s"ipped.
Q;7. 'a*e three subclasses of the Co*ponent class.
?ox.Biller, ?utton, .anvas, .hec"box, .hoice, .ontainer, Habel, Hist, <crollbar, or 3ext.omponent
Q;9. What is the ?re/orianCalendar class?
3he Ore#orian.alendar provides support for traditional >estern calendars.
Q;;. Which Container *ethod is used to cause a container to be laid out and redispla+ed?
validate!$
Q;<. What is the purpose of the :unti*e class?
3he purpose of the 1untime class is to provide access to the *ava runtime system.
Q;>. Cow *an+ ti*es *a+ an objectEs finali=e12 *ethod be invoked b+ the
/arba/e collector?
An ob(ect%s finaliFe!$ method may only be invo"ed once by the #arba#e collector.
Q<@. What is the purpose of the finall+ clause of a tr+Jcatchfinall+ state*ent?
3he finally clause is used to provide the capability to execute code no matter +hether or not an
exception is thro+n or cau#ht.
Q<1. What is the ar/u*ent t+pe of a pro/ra*Es *ain12 *ethod?
A pro#ram%s main!$ method ta"es an ar#ument of the <trin#RS type.
Q<2. Which 6ava operator is ri/ht associative?
3he T operator is ri#ht associative.
Q<0. What is the #ocale class?
3he Hocale class is used to tailor pro#ram output to the conventions of a particular
#eo#raphic, political, or cultural re#ion.
Q<3. Can a double value be cast to a b+te?
Ces, a double value can be cast to a byte.
Q<7. What is the difference between a break state*ent and a continue state*ent?
A brea" statement results in the termination of the statement to +hich it applies !s+itch, for, do, or
+hile$. A continue statement is used to end the current loop iteration and return control to the loop
statement.
Q<9. What *ust a class do to i*ple*ent an interface?
It must provide all of the methods in the interface and identify the interface in its
implements clause.
Q<;. What *ethod is invoked to cause an object to be/in executin/ as a separate thread?
3he start!$ method of the 3hread class is invo"ed to cause an ob(ect to be#in executin# as a separate
thread.
Q<<. 'a*e two subclasses of the IextCo*ponent class.
3extBield and 3extArea
Q<>. What is the advanta/e of the eventJdele/ation *odel over the earlier eventinheritance
*odel?
3he event0dele#ation model has t+o advanta#es over the event0inheritance model. Birst, it enables
event handlin# to be handled by ob(ects other than the ones that #enerate the events !or their
containers$. 3his allo+s a clean separation bet+een a component%s desi#n and its use. 3he other
advanta#e of the event0dele#ation model is that it performs much better in applications +here many
events are #enerated. 3his performance improvement is due to the fact that the event0dele#ation
model does not have to repeatedly process unhandled events, as is the case of the event0inheritance
model.
Q>@. Which containers *a+ have a )enu-ar?
Brame
Q>1. Cow are co**as used in the intiali=ation and iteration parts of a for state*ent?
.ommas are used to separate multiple statements +ithin the initialiFation and iteration parts of a for
statement.
Q>2. What is the purpose of the wait12$ notif+12$ and notif+All12 *ethods?
3he +ait!$,notify!$, and notifyAll!$ methods are used to provide an efficient +ay for threads to +ait for
a shared resource. >hen a thread executes an ob(ect%s +ait!$ method, it enters the +aitin# state. It
only enters the ready state after another thread invo"es the ob(ect%s notify!$ or notifyAll!$ methods..
Q<>. What is the advanta/e of the eventJdele/ation *odel over the earlier eventinheritance
*odel?
3he event0dele#ation model has t+o advanta#es over the event0inheritance model. Birst, it enables
event handlin# to be handled by ob(ects other than the ones that #enerate the events !or their
containers$. 3his allo+s a clean separation bet+een a component%s desi#n and its use. 3he other
advanta#e of the event0dele#ation model is that it performs much better in applications +here many
events are #enerated. 3his performance improvement is due to the fact that the event0dele#ation
model does not have to repeatedly process unhandled events, as is the case of the event0inheritance
model.
Q>@. Which containers *a+ have a )enu-ar?
Brame
Q>1. Cow are co**as used in the intiali=ation and iteration parts of a for state*ent?
.ommas are used to separate multiple statements +ithin the initialiFation and iteration parts of a for
statement.
Q>2. What is the purpose of the wait12$ notif+12$ and notif+All12 *ethods?
3he +ait!$,notify!$, and notifyAll!$ methods are used to provide an efficient +ay for threads to +ait for
a shared resource. >hen a thread executes an ob(ect%s +ait!$ method, it enters the +aitin# state. It
only enters the ready state after another thread invo"es the ob(ect%s notify!$ or notifyAll!$ methods..
Q>0. What is an abstract *ethod?
An abstract method is a method +hose implementation is deferred to a subclass.
Q>3. Cow are 6ava source code files na*ed?
A *ava source code file ta"es the name of a public class or interface that is defined +ithin the file.
A source code file may contain at most one public class or interface. If a public class or interface is
defined +ithin a source code file, then the source code file must ta"e the name of the public class or
interface. If no public class or interface is defined +ithin a source code file, then the filemust ta"e on a
name that is different than its classes and interfaces. <ource code files use the .(ava extension.
Q>7. What is the relationship between the Canvas class and the ?raphics class?
A .anvas ob(ect provides access to a Oraphics ob(ect via its paint!$ method.
Q>9. What are the hi/hJlevel thread states?
3he hi#h0level thread states are ready, runnin#, +aitin#, and dead.
Q>;. What value does read12 return when it has reached the end of a file?
3he read!$ method returns 01 +hen it has reached the end of a file.
Q><. Can a -+te object be cast to a double value?
9o, an ob(ect cannot be cast to a primitive value.
Q>>. What is the difference between a static and a nonstatic inner class?
A non0static inner class may have ob(ect instances that are associated +ith instances of the class%s
outer class. A static inner class does not have any ob(ect instances.
Q1@@. What is the difference between the "trin/ and "trin/-uffer classes?
<trin# ob(ects are constants. <trin#?uffer ob(ects are not.
Q1@1. If a variable is declared as private$ where *a+ the variable be accessed?
A private variable *a+ onl+ be accessed within the class in which it is declared.
Q1@2. What is an objectEs lock and which objectEs have locks?
An objectEs lock is a *echanis* that is used b+ *ultiple threads to obtain s+nchroni=ed
access to the object. A thread *a+ execute a s+nchroni=ed *ethod of an object onl+ after it
has acDuired the objectEs lock. All objects and classes have locks. A classEs lock is acDuired
on the classEs Class object.
Q1@0. What is the ,ictionar+ class?
Ihe ,ictionar+ class provides the capabilit+ to store ke+Jvalue pairs.
Q1@3. Cow are the ele*ents of a -order#a+out or/ani=ed?
Ihe ele*ents of a -order#a+out are or/ani=ed at the borders 1'orth$ "outh$ !ast$ and
West2 and the center of a container.
Q1@7. What is the A operator?
It is referred to as the modulo or remainder operator. It returns the remainder of dividin# the first
operand by the second operand.
Q1@9. When can an object reference be cast to an interface reference?
An ob(ect reference be cast to an interface reference +hen the ob(ect implements the referenced
interface.
Q1@;. What is the difference between a Window and a Gra*e?
3he Brame class extends >indo+ to define a main application +indo+ that can have a menu bar.
Q1@<. Which class is extended b+ all other classes?
3he 'b(ect class is extended by all other classes.
Q1@>. Can an object be /arba/e collected while it is still reachable?
A reachable ob(ect cannot be #arba#e collected. 'nly unreachable ob(ects may be #arba#e collected..
Q11@. Is the ternar+ operator written x + ? = or x ? + = ?
It is +ritten x G y F.
Q111. What is the difference between the Gont and Gont)etrics classes?
3he Bont5etrics class is used to define implementation0specific properties, such as ascent and
descent, of a Bont ob(ect.
Q112. Cow is roundin/ perfor*ed under inte/er division?
3he fractional part of the result is truncated. 3his is "no+n as roundin# to+ard Fero.
Q110. What happens when a thread cannot acDuire a lock on an object?
If a thread attempts to execute a synchroniFed method or synchroniFed statement and is unable to
ac)uire an ob(ect%s loc", it enters the +aitin# state until the loc" becomes available.
Q113. What is the difference between the :eaderBWriter class hierarch+ and the
Input"trea*B%utput"trea* classhierarch+?
3he 1eader7>riter class hierarchy is character0oriented, and the Input<tream7 'utput<tream
class hierarchy is byte0oriented.
Q117. What classes of exceptions *a+ be cau/ht b+ a catch clause?
A catch clause can catch any exception that may be assi#ned to the 3hro+able type. 3his includes the
-rror and -xception types.
Q119. If a class is declared without an+ access *odifiers$ where *a+ the class be accessed?
A class that is declared +ithout any access modifiers is said to have pac"a#e access. 3his means that
the class can only be accessed by other classes and interfaces that are defined +ithin the same
pac"a#e.
Q11;. What is the "i*pleIi*e.one class?
3he <imple3imeUone class provides support for a Ore#orian calendar.
Q11<. What is the )ap interface?
3he 5ap interface replaces the *DI 1.1 Dictionary class and is used associate "eys +ith values.
Q11>. ,oes a class inherit the constructors of its superclass?
A class does not inherit constructors from any of its superclasses.
Q12@. Gor which state*ents does it *ake sense to use a label?
3he only statements for +hich it ma"es sense to use a label are those statements that
can enclose a brea" or continue statement.
Q121. What is the purpose of the "+ste* class?
3he purpose of the <ystem class is to provide access to system resources.
Q122. Which IextCo*ponent *ethod is used to set a IextCo*ponent to the readJ
onl+ state?
set-ditable!$
Q120. Cow are the ele*ents of a Card#a+out or/ani=ed?
3he elements of a .ardHayout are stac"ed, one on top of the other, li"e a dec" of cards.
Q123. Is 55K a valid 6ava operator?
9o, it is not.
Q127. 'a*e the ei/ht pri*itive 6ava t+pes?
3he ei#ht primitive types are byte, char, short, int, lon#, float, double, and boolean.
Q129. Which class should +ou use to obtain desi/n infor*ation about an object?
3he .lass class is used to obtain information about an ob(ect%s desi#n.
Q12;. What is the relationship between clippin/ and repaintin/?
>hen a +indo+ is repainted by the A>3 paintin# thread, it sets the clippin# re#ions to the area of the
+indo+ that re)uires repaintin#.
Q12<. Is LabcL a pri*itive value?
3he <trin# literal =abc= is not a primitive value. It is a <trin# ob(ect.
Q12>. What is the relationship between an eventJlistener interface and an eventJadapter
class?
An event0listener interface defines the methods that must be implemented by an event handler for a
particular "ind of event. An event adapter provides a default implementation of an event0listener
interface.
Q10@. What restrictions are placed on the values of each case of a switch state*ent?
Durin# compilation, the values of each case of a s+itch statement must evaluate to a value that can
be promoted to an int value.
Q101. What *odifiers *a+ be used with an interface declaration?
An interface may be declared as public or abstract.
Q102. Is a class a subclass of itself?
A class is a subclass of itself.
Q100. What is the hi/hestJlevel event class of the eventdele/ation *odel?
3he (ava.util.-vent'b(ect class is the hi#hest0level class in the event0dele#ation class hierarchy.
Q103. What event results fro* the clickin/ of a button?
3he Action-vent event is #enerated as the result of the clic"in# of a button.
Q107. Cow can a ?&I co*ponent handle its own events?
A component can handle its o+n events by implementin# the re)uired event0listener interface and
addin# itself as its o+n event listener.
Q109. What is the difference between a while state*ent and a do state*ent?
A +hile statement chec"s at the be#innin# of a loop to see +hether the next loop iteration should
occur. A do statement chec"s at the end of a loop to see +hether the next iteration of a loop should
occur. 3he do statement +ill al+ays execute the body of a loop at least once.
Q10;. Cow are the ele*ents of a ?rid-a/#a+out or/ani=ed?
3he elements of a Orid?a#Hayout are or#aniFed accordin# to a #rid. 2o+ever, the elements are of
different siFes and may occupy more than one ro+ or column of the #rid. In addition, the ro+s and
columns may have different siFes.
Q10<. What advanta/e do 6avaEs la+out *ana/ers provide over traditional windowin/
s+ste*s?
*ava uses layout mana#ers to lay out components in a consistent manner across all +indo+in#
platforms. <ince *ava%s layout mana#ers aren%t tied to absolute siFin# and positionin#, they are able to
accomodate platform0specific differences amon# +indo+in# systems.
Q10>. What is the Collection interface?
3he .ollection interface provides support for the implementation of a mathematical ba# V an
unordered collection of ob(ects that may contain duplicates.
Q13@. What *odifiers can be used with a local inner class?
A local inner class may be final or abstract.
Q131. What is the difference between static and nonJstaticvariables?
A static variable is associated +ith the class as a +hole rather than +ith specific instances of a class.
9on0static variables ta"e on uni)ue values +ith each ob(ect instance.
Q132. What is the difference between the paint12 and repaint12 *ethods?
3he paint!$ method supports paintin# via a Oraphics ob(ect. 3he repaint!$ method is used to cause
paint!$ to be invo"ed by the A>3 paintin# thread.
Q130. What is the purpose of the Gile class?
3he Bile class is used to create ob(ects that provide access to the files and directories of a local file
system.
Q133. Can an exception be rethrown?
Ces, an exception can be rethro+n.
Q137. Which )ath *ethod is used to calculate the absolute value of a nu*ber?
3he abs!$ method is used to calculate absolute values.
Q139. Cow does *ultithreadin/ take place on a co*puter with a sin/le C(&?
3he operatin# system%s tas" scheduler allocates execution time to multiple tas"s. ?y )uic"ly s+itchin#
bet+een executin# tas"s, it creates the impression that tas"s execute se)uentially.
Q13;. When does the co*piler suppl+ a default constructor for a class?
3he compiler supplies a default constructor for a class if no other constructors are provided.
Q13<. When is the finall+ clause of a tr+JcatchJfinall+ state*ent executed?
3he finally clause of the try0catch0finally statement is al+ays executed unless the thread of execution
terminates or an exception occurs +ithin the execution of the finally clause.
Q13>. Which class is the i**ediate superclass of the Container class?
.omponent
Q17@. If a *ethod is declared as protected$ where *a+ the *ethod be accessed?
A protected method may only be accessed by classes or interfaces of the same pac"a#e or by
subclasses of the class in +hich it is declared.
Q171. Cow can the Checkbox class be used to create a radio button?
?y associatin# .hec"box ob(ects +ith a .hec"boxOroup.
Q172. Which nonJ&nicode letter characters *a+ be used as the first character of an
identifier?
3he non04nicode letter characters W and X may appear as the first character of an identifier
Q170. What restrictions are placed on *ethod overloadin/?
3+o methods may not have the same name and ar#ument list but different return types.
Q173. What happens when +ou invoke a threadEs interrupt *ethod while it is sleepin/ or
waitin/?
>hen a tas"%s interrupt!$ method is executed, the tas" enters the ready state. 3he next time the tas"
enters the runnin# state, an Interrupted-xception is thro+n.
Q177. What is castin/?
3here are t+o types of castin#, castin# bet+een primitive numeric types and castin# bet+een ob(ect
references. .astin# bet+een numeric types is used to convert lar#er values, such as double values, to
smaller values, such as byte values. .astin# bet+een ob(ect references is used to refer to an ob(ect by
a compatible class, interface, or array type reference.
Q179. What is the return t+pe of a pro/ra*Es *ain12 *ethod?
A pro#ram%s main!$ method has a void return type.

Q17;. 'a*e four Container classes.
>indo+, Brame, Dialo#, BileDialo#, /anel, Applet, or <croll/ane
Q17<. What is the difference between a Choice and a #ist?
A .hoice is displayed in a compact form that re)uires you to pull it do+n to see the list of available
choices. 'nly one item may be selected from a .hoice. A Hist may be displayed in such a +ay that
several Hist items are visible. A Hist supports the selection of one or more Hist items.
Q17>. What class of exceptions are /enerated b+ the 6ava runJti*e s+ste*?
3he *ava runtime system #enerates 1untime-xception and -rror exceptions.
Q19@. What class allows +ou to read objects directl+ fro* a strea*?
3he 'b(ectInput<tream class supports the readin# of ob(ects from input streams.

Q191. What is the difference between a field variable and a local variable?
A field variable is a variable that is declared as a member of a class. A local variable is a variable that
is declared local to a method.
Q192. &nder what conditions is an objectEs finali=e12 *ethod invoked b+ the /arba/e
collector?
3he #arba#e collector invo"es an ob(ect%s finaliFe!$ method +hen it detects that the ob(ect has
become unreachable.
Q190. Cow are this12 and super12 used with constructors?
this!$ is used to invo"e a constructor of the same class. super!$ is used to invo"e a superclass
constructor.
Q193. What is the relationship between a *ethodEs throws clause and the exceptions that
can be thrown durin/ the*ethodEs execution?
A method%s thro+s clause must declare any chec"ed exceptions that are not cau#ht +ithin the body of
the method.
Q197. What is the difference between the 6,F 1.@2 event *odel and the eventJdele/ation
*odel introduced with6,F 1.1?
3he *DI 1.J2 event model uses an event inheritance or bubblin# approach. In this model, components
are re)uired to handle their o+n events. If they do not handle a particular event, the event is
inherited by !or bubbled up to$ the component%s container. 3he container then either handles the
event or it is bubbled up to its container and so on, until the hi#hest0level container has been tried..In
the event0dele#ation model, specific ob(ects are desi#nated as event handlers for O4I components.
3hese ob(ects implement event0listener interfaces. 3he event0dele#ation model is more efficient than
the event0inheritance model because it eliminates the processin# re)uired to support the bubblin# of
unhandled events.
Q199. Cow is it possible for two "trin/ objects with identical values not to be eDual under
the KK operator?
3he TT operator compares t+o ob(ects to determine if they are the same ob(ect in memory. It is
possible for t+o <trin# ob(ects to have the same value, but located indifferent areas of memory.
Q19;. Wh+ are the *ethods of the )ath class static?
<o they can be invo"ed as if they are a mathematical code library.
Q19<. What Checkbox *ethod allows +ou to tell if a Checkbox is checked?
#et<tate!$
Q19>. What state is a thread in when it is executin/?
An executin# thread is in the runnin# state.
Q1;@. What are the le/al operands of the instanceof operator?
3he left operand is an ob(ect reference or null value and the ri#ht operand is a class, interface, or
array type.
Q1;1. Cow are the ele*ents of a ?rid#a+out or/ani=ed?
3he elements of a Orid?ad layout are of e)ual siFe and are laid out usin# the s)uares of a #rid.
Q1;2. What an IB% filter?
An I7' filter is an ob(ect that reads from one stream and +rites to another, usually alterin# the data in
some +ay as it is passed from one stream to another.
Q1;0. If an object is /arba/e collected$ can it beco*e reachable a/ain?
'nce an ob(ect is #arba#e collected, it ceases to exist. It can no lon#er become reachable a#ain.
Q1;3. What is the "et interface?
3he <et interface provides methods for accessin# the elements of a finite mathematical set. <ets do
not allo+ duplicate elements.
Q1;7. What classes of exceptions *a+ be thrown b+ a throw state*ent?
A thro+ statement may thro+ any expression that may be assi#ned to the 3hro+able type.
Q1;9. What are ! and (I?
- is the base of the natural lo#arithm and /I is mathematical value pi.
Q1;;. Are true and false ke+words?
3he values true and false are not "ey+ords.
Q1;<. What is a void return t+pe?
A void return type indicates that a method does not return a value.
Q1;>. What is the purpose of the enable!vents12 *ethod?
3he enable-vents!$ method is used to enable an event for a particular ob(ect. 9ormally, an event is
enabled +hen a listener is added to an ob(ect for a particular event. 3he enable-vents!$ method is
used by ob(ects that handle events by overridin# their eventdispatch methods.
Q1<@. What is the difference between the Gile and :ando*AccessGile classes?
3he Bile class encapsulates the files and directories of the local file system. 3he 1andomAccessBile
class provides the methods needed to directly access data contained in any part of a file.
Q1<1. What happens when +ou add a double value to a "trin/?
3he result is a <trin# ob(ect.
Q1<2. What is +our platfor*Es default character encodin/?
If you are runnin# *ava on -n#lish >indo+s platforms, it is probably .p1252. If you are runnin# *ava
on -n#lish <olaris platforms, it is most li"ely NN5KX1..
Q1<0. Which packa/e is alwa+s i*ported b+ default?
3he (ava.lan# pac"a#e is al+ays imported by default.
Q1<3. What interface *ust an object i*ple*ent before it can be written to a strea* as an
object?
An ob(ect must implement the <erialiFable or -xternaliFable interface before it can be +ritten to a
stream as an ob(ect.
Q1<7. Cow are this and super used?
this is used to refer to the current ob(ect instance. super is used to refer to the variables and methods
of the superclass of the current ob(ect instance.
Q1<9. What is the purpose of /arba/e collection?
3he purpose of #arba#e collection is to identify and discard ob(ects that are no lon#er needed by a
pro#ram so that their resources may be reclaimed and reused.
Q1<;. What is a co*pilation unit?
A compilation unit is a *ava source code file.
Q1<<. What interface is extended b+ AWI event listeners?
All A>3 event listeners extend the (ava.util.-ventHistener interface.
Q1<>. What restrictions are placed on *ethod overridin/?
, 'verridden methods must have the same name, ar#ument list, and return type.
, 3he overridin# method may not limit the access of the method it overrides.
, 3he overridin# method may not thro+ any exceptions that may not be thro+nby the overridden
method.
Q1>@. Cow can a dead thread be restarted?
A dead thread cannot be restarted.
Q1>1. What happens if an exception is not cau/ht?
An uncau#ht exception results in the uncau#ht-xception!$ method of the thread%s
3hreadOroup bein# invo"ed, +hich eventually results in the termination of the pro#ram in +hich it is
thro+n.
Q1>2. What is a la+out *ana/er?
A layout mana#er is an ob(ect that is used to or#aniFe components in a container.
Q1>0. Which arith*etic operations can result in the throwin/ of an Arith*etic!xception?
Inte#er 7 and Y can result in the thro+in# of an Arithmetic-xception.
Q1>3. What are three wa+s in which a thread can enter the waitin/ state?
A thread can enter the +aitin# state by invo"in# its sleep!$ method, by bloc"in# on I7', by
unsuccessfully attemptin# to ac)uire an ob(ect%s loc", or by invo"in# an ob(ect%s +ait!$ method. It can
also enter the +aitin# state by invo"in# its !deprecated$ suspend!$ method.
Q1>7. Can an abstract class be final?
An abstract class may not be declared as final.
Q1>9. What is the :esource-undle class?
3he 1esource?undle class is used to store locale0specific resources that can be loaded by a pro#ram to
tailor the pro#ram%s appearance to the particular locale in +hich it is bein# run.
Q1>;. What happens if a tr+JcatchJfinall+ state*ent doesnot have a catch clause to handle
an exception that is
thrown within the bod+ of the tr+ state*ent?
3he exception propa#ates up to the next hi#her level try0catch statement !if any$ or results in the
pro#ram%s termination.
Q1><. What is nu*eric pro*otion?
9umeric promotion is the conversion of a smaller numeric type to a lar#er numeric type, so that
inte#er and floatin#0point operations may ta"e place. In numerical promotion, byte, char, and short
values are converted to int values. 3he int values are also converted to lon# values, if necessary. 3he
lon# and float values are converted to double values, as re)uired.
Q1>>. What is the difference between a "crollbar and a "croll(ane?
A <crollbar is a .omponent, but not a .ontainer. A <croll/ane is a .ontainer. A <croll/ane handles its
o+n events and performs its o+n scrollin#.
Q2@@. What is the difference between a public and a nonpublic class?
A public class may be accessed outside of its pac"a#e. A non0public class may not be accessed outside
of its pac"a#e.
Q2@1. Io what value is a variable of the boolean t+pe auto*aticall+ initiali=ed?
3he default value of the boolean type is false.
Q2@2. Can tr+ state*ents be nested?
3ry statements may be tested.
Q2@0. What is the difference between the prefix and postfix for*s of the 44 operator?
3he prefix form performs the increment operation and returns the value of the increment operation.
3he postfix form returns the current value all of the expression and then performs the increment
operation on that value.
Q2@3. What is the purpose of a state*ent block?
A statement bloc" is used to or#aniFe a se)uence of statements as a sin#le statement #roup.
Q2@7. What is a 6ava packa/e and how is it used?
A 6ava packa/e is a na*in/ context for classes and interfaces. A packa/e is used to create a
separate na*espace for /roups of classes and interfaces. (acka/es are also used to
or/ani=e related classes and interfaces into a sin/le A(I unit and to control accessibilit+ to
these classes and interfaces.
Q2@9. What *odifiers *a+ be used with a topJlevel class?
A topJlevel class *a+ be public$ abstract$ or final.
Q2@;. What are the %bject and Class classes used for?
Ihe %bject class is the hi/hestJlevel class in the 6ava class hierarch+. Ihe Class class is
used to represent the classes and interfaces that are loaded b+ a 6ava pro/ra* ..
Q2@<. Cow does a tr+ state*ent deter*ine which catch clause should be used to handle an
exception?
When an exception is thrown within the bod+ of a tr+ state*ent$ the catch clauses of the tr+
state*ent are exa*ined in the order in which the+ appear. Ihe first catch clause that is
capable of handlin/ the exception is executed. Ihe re*ainin/ catch clauses are i/nored.
Q2@>. Can an unreachable object beco*e reachable a/ain?
An unreachable ob(ect may become reachable a#ain. 3his can happen +hen the ob(ect%s finaliFe!$
method is invo"ed and the ob(ect performs an operation +hich causes it to become accessible to
reachable ob(ects.
Q21@. When is an object subject to /arba/e collection?
An ob(ect is sub(ect to #arba#e collection +hen it becomes unreachable to the pro#ram in +hich it is
used.
Q211. What *ethod *ust be i*ple*ented b+ all threads?
All tas"s must implement the run!$ method, +hether they are a subclass of 3hread or implement the
1unnable interface.
Q212. What *ethods are used to /et and set the text label displa+ed b+ a -utton object?
#etHabel!$ and setHabel!$
Q210. Which Co*ponent subclass is used for drawin/ and paintin/?
.anvas
Q213. What are s+nchroni=ed *ethods and s+nchroni=ed state*ents?
<ynchroniFed methods are methods that are used to control access to an ob(ect. A thread only
executes a synchroniFed method after it has ac)uired the loc" for the method%s ob(ect or class.
<ynchroniFed statements are similar to synchroniFed methods. A synchroniFed statement can only be
executed after a thread has ac)uired the loc" for the ob(ect or class referenced in the synchroniFed
statement.
Q217. What are the two basic wa+s in which classes that can be run as threads *a+ be
defined?
A thread class may be declared as a subclass of 3hread, or it may implement the 1unnable interface.
Q219. What are the proble*s faced b+ 6ava pro/ra**ers who donEt use la+out *ana/ers?
>ithout layout mana#ers, *ava pro#rammers are faced +ith determinin# ho+ their O4I +ill be
displayed across multiple +indo+in# systems and findin# a common siFin# and positionin# that +ill
+or" +ithin the constraints imposed by each +indo+in# system.
Q21;. What is the difference between an if state*ent and a switch state*ent?
3he if statement is used to select amon# t+o alternatives. It uses a boolean expression to decide
+hich alternative should be executed. 3he s+itch statement is used to select amon# multiple
alternatives. It uses an int expression to determine +hich alternative should be executed.
Q21<. What happens when +ou add a double value to a "trin/?
3he result is a <trin# ob(ect.
Q21>. What is the #ist interface?
3he Hist interface provides support for ordered collections of ob(ects.
-xception
1.What is an !xception?
Ans.An un+anted, unexpected event that disturbs normal flo+ of the pro#ram is called
-xception.-xample Bile9otBond-xception.
Q2.What is the purpose of !xception Candlin/?
Ans.3he main purpose of -xception 2andlin# is for #raceful termination of the pro#ram.
Q0.What is the *eanin/ of !xception Candlin/?
Ans. -xception 2andlin# doesnAt mean repairin# an -xception, +e have to define alternative +ay to
continue rest of the code normally.
-xample If our pro#rammin# re)uirement is to read the data from the file locatin# at Hondon but at
1untime if Hondon file is not available then +e have to use local file alternatively to continue rest of
pro#ram normally. 3his is nothin# but -xception 2andlin#.
Q3.!xplain ,efault !xception Candlin/ )echanis* in java?
Ans.If an exception raised, the method in +hich itAs raised is responsible for the creation of
-xceptions ob(ect by includin# the follo+in# information
9ame of the -xception
Description of the -xception
<tac" 3race
After creatin# -xception ob(ect the method handover it to the *L5.
*L5 chec"s for -xception 2andlin# code in that method.
If the method doesnAt contain any -xception handlin# code then *L5 terminates the method
abnormally and removes the correspondin# entry from the stac".
*L5 identify the caller method and chec"s for -xception 2andlin# code in that method. If the
caller doesnAt contain any exception handlin# code then *L5 terminates that method
abnormally and removes the correspondin# entry from the stac".
3his process +ill be continue until main!$ method.
If the main!$ method also doesnAt contain exception handlin# code the *L5 terminates that
main!$ method and removes the correspondin# entry from the stac".
*ust before terminatin# the pro#ram abnormally *L5 handovers the responsibility of exception
handlin# to the Default -xception 2andler +hich is the component of *L5.
Default -xception 2andler (ust print exception information to the consol in the follo+in# format
9ame of -xception Description
<tac" 3race !Hocation of the -xception$
Q7.What is the purpose of tr+?
Ans >e should maintain all ris"y code inside the try bloc".
Q9. What is the purpose of catch block?
Ans.>e have to maintain all -xception 2andlin# code inside the catch bloc".
Q;. Is tr+ with *ultiple catch block is possible?
Ans. 3he +ay of handlin# an exception is varied from exception to exception compulsory +e have to
+rite a separate catch bloc" for every exception. 2ence try +ill multiple catch bloc" is possible and it
is recommended to use.
-xample
try6
771is"y code
;
catch!I'-xception e$
6
772ndlin# code for I'-xception
;
catch!Arithmetic-xception e$
6
77handlin# code for A-
;
catch!9ull/ointer-xcetpion e$
6
77 handlin# code for 9/-
;
catch!-xception e$
6
77default exception handlin# code
;
Q<. If tr+ with *ultiple catch block present is order of catch blocks i*portant in which
order we have to take?
Ans. If try +ith multiple catch bloc" present then the order of catch bloc" is very important it should
be from child to parent but not from parent to child.
Q>. What are various *ethods to print !xception infor*ation? and differentiate the*.
Ans.
3hro+able class defines the follo+in# method to print exception or error information .
1. print"tackIrace12 0 3his method print exception information in the follo+in# format.
'a*e of the !xception ,escription
"tackIrace
2.to"trin/120 3his method print exception information in the follo+in# format.
'a*e of the !xception ,escription
0./et)essa/e120 3his method prints only description of the exception.
,escription
Q1@.If an exception rised inside catch block then what will happen?
Ans. If an exception raised inside catch bloc" and it is not part of any try bloc" then it is al+ays
abnormal termination.
Q11. Is it possible to take tr+$ catch inside tr+ block?
Ans. Ces, It is possible to ta"e try, catch inside try bloc". 3hat is nestin# of try catch is possible.
Q12.Is it possible to take tr+$ catch inside catch block?
Ans. Ces, It is possible to ta"e try, catch inside catch bloc".
Q10. Is it possible to take tr+ without catch?
Ans. Ces, it is possible to ta"e try +ithout catch but compulsory finally bloc" should be available.
Q13. What is the purpose of finall+ block?
Ans. 3he main purpose of finally bloc" is, to maintain the cleanup code. 3his bloc" +ill execute
al+ays.
Q17. Is finall+ block will be execute alwa+s?
Ans. Ces finally bloc" +ill be executed al+ays irrespective of +hether exception raised or not raised
+hether exceptions are handled or not handle. 3here is one situation +here the finally bloc" +onAt be
executed if the *L5 is #oin# to be shutdo+n.
Q19. In which situation finall+ block will not executed?
Ans. 3here is one situation +here the finally bloc" +onAt be executed if +e are usin# system.exit!J$
explicitly then *L5 itself +ill be shutdo+n and there is no chance of executin# finally bloc".
Q1;. If return state*ent present inside tr+ is finall+ block will be executed?
Ans. Ces, if return statement present inside try, then also finally bloc" +ill be executed. finally bloc"
+ill dominate return statement also.
Q1<. What is the difference between final$ finall+ and finali=e12?
Ans. finalJ final is a modifier applicable for variables$ *ethods and classes. final variable means
constant and reassi#nment is not possible. final *ethod means implementation is final in the child
classes +e canAt override. final classmeans it +onAt participate in inheritance and child class creation
is not possible.
finall+J It is a block associated +ith try catch to *aintain cleanup code. Binally bloc" +ill be
executed al+ays irrespective of +hether exception is raised or not raised or +hether the exception is
handle or not handle.
finali=e120 It is a *ethod, Oarba#e collector al+ays calls this method (ust before destroyin# any
ob(ect to perform cleanup activities.
Q1>. Is it possible to write an+ state*ent between tr+Jcatch and finall+?
Ans. 9o, it is not possible to +rite any statement bet+een try catch and finally. If +e +ill try to +rite
any statement bet+een them then +e +ill #et compile time error.
Q2@. Is it possible to take two finall+ blocks for the sa*e tr+?
Ans. 9o, it is not possible to ta"e t+o finally bloc"s for the same try. If +e try to ta"e then +e +ill #et
compile time error.
Q21. Is s+ntax tr+Jfinall+Jcatch is valid ?
Ans. 9o, this syntax is not valid. It should be li"e try0catch0finally then only code +ill compile.
Q22. What is the purpose of throw?
Ans. <ometimes +e can create -xception ob(ect explicitly and +e can handover that exception ob(ect
to the *L5 explicitly by thro+ "ey+ord.
3he purpose of thro+ "ey+ord is to handover our created exception ob(ect explicitly to the *L5.
!xa*ple1
class 3est6
public static void main!<trin#RS ar#s$6
<ystem.out.println!1J7J$:
;
;
In this case Arithmetic-xception ob(ect created implicitly and handover to the *L5
automatically by the main method.
!xa*ple2
.lass 3est6
/ublic static void main!<trin#RS ar#s$6
3hro+ ne+ Arithmetic-xception!Z7by Uero[$:
;
;
In this case creation of an exception ob(ect and handover to the *L5 explicitly by the
pro#rammer.
Q20. Is it possible to throw an !rror?
Ans. Ces, It is possible to thro+ any 3hro+able type includin# -rror.
Q23. Is it possible to throw an+ java object?
Ans. 9o, +e can use thro+ "ey+ord only for thro+able ob(ects other+ise +e +ill #et compile time
error sayin# incompatible type.
Q27. After throw is it allow to take an+ state*ent directl+?
Ans. After thro+ statement +e are not allo+ to place any statement directly violation leads to compile
time error sayin# 4nreachable <tatement.
Q29. What is the purpose of throws?
Ans. 3he main purpose of thro+s "ey+ord is to dele#ate the responsibilities of exception handlin# to
the caller. It re)uires in the case of chec"ed exception.
Q2;. What is the difference between throw and throws?
Ans. <ometimes +e can create -xception ob(ect explicitly and +e can handover that exception ob(ect
to the *L5 explicitly by thro+ "ey+ord.3he main purpose of thro+ "ey+ord is to handover our created
exception ob(ect explicitly to the *L5. 3he main purpose of thro+s "ey+ord is to dele#ate the
responsibilities of exception handlin# to the caller. It re)uires in the case of chec"ed exception.
Q2<. What is the difference between throw and thrown?
Ans. 3here is no terminolo#y of thro+n in (ava.
Q2>. Is it possible to use throws ke+word for an+ java class ?
Ans. 9o, +e can use thro+s "ey+ord only for 3hro+able classes. 'ther+ise +e +ill #et compile time
error sayin# Incompatible types.
Q0@. If we are takin/ catch block for an exception but there is no chance of risin/ that
exception in tr+ then what will happen?
Ans. If there is no chance of raisin# an exception in try then +e are not allo+ to +rite catch bloc" for
that exception violation leads to compile time error. ?ut this rule is applicable only for fully chec"ed
exception.
Q01. !xplain !xception Candlin/ ke+word?
Ans. !xception Candlin/ ke+word
3ry 0 3o maintain 1is"y code.
.atch0 3o maintain -xception 2andlin# code.
Binally0 3o maintain the clean up code.
3hro+0 3o handover our created exception ob(ect to the *L5 explicitly.
3hro+s0 3o dele#ate the responsibilities of -xception 2andlin# to the caller.
Q02. Which class act as root for entire java !xception hierarch+?
Ans. 3hro+able class act as root for entire (ava -xception hierarchy.
Q00. What is the difference between !rror and !xception?
Ans. 3hro+able class contain t+o child classes.
!xceptionJ 3hese are mostly caused by our pro#ram and are recoverable.
!rror0 3hese are not caused by our pro#ram, mostly caused by la"e of system resources.
3hese are non recoverable.
Q03. What is difference between checked exception and unchecked exception?
Ans. 3he exceptions +hich are chec"ed by the compiler for smooth execution of the pro#ram at
1untime is called chec"ed exception. -xample I'-xception, Interrupted-xception.3he exceptions
+hich are not chec"ed by the compiler are called unchec"ed exception. -xample
Arithmetic-xception,1untime-xception.
Q07.What is difference between partiall+ checked and full+ checked !xception?
Ans. A chec"ed exception is said to be fully chec"ed if and only if all the child classes also chec"ed
other+ise it is called partially chec"ed exception.
-xample
I'-xception0 fully chec"ed exception
-xception0 partially chec"ed exception
3hro+able0 partially chec"ed exception
1untime-xception0 unchec"ed exception
Q09. What is a custo*i=ed !xception?
Ans. <ometimes based on our pro#rammin# re)uirement +e have to create our o+n exception such
type of exception are called customiFe -xception.
-xample
3ooCoun#-xception
3oo'ld-xception
InsufficientBund-xception
Q0;. !xplain the process of creatin/ the custo*i=ed !xception.
Ans. Creatin/ custo*i=ed !xception
.lass 3ooCoun#-xception extends 1untime-xception6
3ooCoun#-xcetpion!<trin# desc$6
<uper!desc$:
;
;
.lass 3oo'ld-xception extends 1untime-xception
6
3oo'ld-xception!<trin# desc$6
super!desc$:
;
;
.lass cust-xcepiton6
/ublic static void main!<trin#RS ar#s$6
Int a#eTInte#er.parseInt!ar#sRJS$:
If!a#eM6J$
6
3hro+ ne+ 3ooCoun#-xception!Z/lease +ait some more time, definitely you +ill #et best match[$:
;
-lse if!a#e\1N$
6
3hro+ ne+ 3oo'ld-xception!ZCour a#e is already crossed of marria#e, no chance to #ettin#
marria#e[$:
;
-lse
6
<ystem.out.println!Z.on#ratulation] Cou +ill #et match details soon by your
email[$:
;
;

Q0<. !xplain control flow in tr+$ catch$ finall+.
Ans. 3ry6
<tatement1:
<tatement2:
<tatement3:
;
.atch!^ e$6
<tatement4:
;
Binally6
<tatement5:
;
<tatement6:
.ase1
If there is no -xception then output is
<tatement1
<tatement2
<tatement3
<tatement5
<tatement6
9ormal termination
.ase2
If an exception raised at statement2 and correspondin# catch bloc" has matched then output is
<tatement1
<tatement4
<tatement5
<tatement5
9ormal termination
.ase3
An exception raised at statement2 and correspondin# catch has not matched then output is
<tatement1
<tatement5
Abnormal termination
.ase4
An exception occurs at statement4 it al+ays Abnormal termination but before that finally bloc" +ill be
executed and output is
<tatement1
<tatement2
<tatement5
Abnormal termination
.ase5
If an exception raised at statement5 or statement6, it is al+ays abnormal termination.
Q0>. Can +ou /ive the *ost co**on occurred exception in +our previous project.
Ans. 9ull/ointer-xception, ArrayIndex'utof?ound-xception, <tac"'verBlo+-rror, .lass.ast-xception,
9o.lassDefBound-rror, -xceptionInitiliFer-rror, Ille#alAr#ument-xception, 9umberBormat-xception,
Ille#al<tate-xception, Assertion-rror.
Q3@. !xplain the cases where +ou used !xception Candlin/ in +our previous project?
Ihreadin/
Q1. What is )ultitaskin/?
Ans. -xecutin# several tas" simultaneously is called multitas"in#.
Q2. What is the difference between processJbased and IhreadJbased )ultitaskin/?
Ans.(rocessJbased *ultitaskin/J -xecutin# several tas" simultaneously +here each tas" is a
separate independent process such type of multitas"in# is called process based 5ultitas"in#.
-xample0>hile typin# a pro#ram in the editor +e can listen 5/3 audio son#s. At the same time +e
do+nload a file from the net. all these tas" are executin# simultaneously and each tas" is a
separate independent pro#ram. hence it is process based multitas"in#. It is best suitable at operatin#
system level. IhreadJbased *ultitaskin/J -xecutin# several tas" simultaneously +here each tas"
is a separate independent part of the same pro#ram is called 3hread0based multitas"in#. and every
independent part is called a thread. 3his type of multitas"in# is best suitable at pro#rammatic level.
Q0. What is )ultithreadin/ and explain its application areas?
Ans. -xecutin# several thread simultaneously +here each thread is a separate independent part of the
same pro#ram is calledmultithreadin#. *ava lan#ua#e provides inbuilt support for multithreadin# by
definin# a reach library, classes and interfaces li"e 3hread, 3hreadOroup, 1unnable etc. 3he main
important application area of multithreadin# are video #ames implementation, animation
development, multimedia #raphics etc.
Q3.What is advanta/e of )ultithreadin/?
Ans. 3he main advanta#e of multithreadin# is reduces response time and improves performance of the
system.
Q7. When co*pared with C44 what is the advanta/e in java with respect to
)ultithreadin/?
Ans.*ava lan#ua#e provides inbuilt support for multithreadin# by definin# a reach library, classes and
interfaces li"e 3hread, 3hreadOroup, 1unnable etc. ?ut in c@@ there is no inbuilt support for
multithreadin#.
Q9. In how *an+ wa+s we can define a Ihread? A*on/ extendin/ Ihread and i*ple*entin/
:unnable which is reco**ended?
Ans. >e can define a 3hread in the follo+in# t+o +ays
1. by extendin# 3hread class or
2. by implementin# 1unnable interface.
Amon# the t+o +ays of definin# a thread implementin# 1unnable mechanism is al+ays recommended.
In the first approach as our 3hread class already extendin# 3hread there is no chance
of extendin# any other. 2ence, +e missin# the "ey benefit of oops!inheritance properties$.
Q;. What is the difference between t.start12 and t.run12 *ethod?
Ans. In the case of t.start!$ method, a ne+ thread +ill be created +hich is responsible for the
execution of run!$ method.
?ut in the case of t.run!$ method no ne+ thread +ill be created main thread executes run!$
method (ust li"e a normal method call.
Q<. !xplain about Ihread "cheduler?
Ans. If multiple threads are +aitin# for #ettin# the chance for executin# then +hich thread +ill #et
chance first decided by 3hread <cheduler. It is the part of *L5 and its behavior is
vendor dependent and +e canAt expect exact output.>henever the situation comes to multithreadin#
the #uarantee behavior is very0 very lo+.
Q>. If we are not overridin/ run12 *ethod what will happened?
Ans.If +e are not overridin# run!$ method then 3hread class run!$ method +ill executed +hich has
empty implementation and hence +e +ill not #et any output.
Q1@.Is overloadin/ of run12 *ethod is possible?
Ans.Ces, +e can overload run!$ method but 3hread class start!$ method al+ays invo"es no0ar#ument
run!$ method only. 3he other run!$ method +e have to call explicitly then only +ill be executed.
Q11.Is it possible to override start12 *ethod?
Ans. Ces it is possible. ?ut not recommended.
Q12.If we are overridin/ start12 *ethod then what will happen?
Ans. It +e are overridin# start!$ method then our o+n start!$ method +ill be executed (ust li"e a
normal method call. In this case no ne+ 3hread +ill be created.
Q10. !xplain life c+cle of a Ihread?
Ans. 'nce +e create a 3hread ob(ect then the 3hread is said to be in 9e+7?orn state once +e call
t.start!$ method no+ the 3hread +ill be entered into ready71unnable state that is 3hread is ready to
execute. If 3hread <cheduler allocates ./4 no+ the 3hread +ill entered into the 1unnin# state and
start execution of run!$ method. After completin# run!$ method the 3hread entered into Dead <tate.
Q13. What is the i*portance of Ihread class start12 *ethod?
Ans. <tart!$ method present in 3hread class performin# all lo+ level (oinin# formalities for the ne+ly
created thread li"e re#isterin# thread +ith 3hread <cheduler etc and then start!$ method invo"in#
run!$ method.As the start!$ method is doin# all lo+ level mandatory activities, /ro#rammer has to
concentrate only on run!$ method to define the (ob. 2ence, start!$ method is a bi#assistant to the
pro#rammer.>ithout executin# 3hread class start!$ method there is no chance of startin# a ne+
3hread.
Q17. After startin/ a Ihread if we tr+in/ to restart the sa*e thread once a/ain what will
happen?
Ans. After startin# a 3hread restartin# of the same 3hread once a#ain is not allo+ed violation leads to
1untime -xception sayin# Ille#al3hread<tate-xception.
Q19. !xplain Ihread class constructors?
Ans. 3here are ei#ht constructors are available in 3hread class
1. 3hread tTne+ 3hread!$:
2. 3hread tTne+ 3hread!1unnable r$:
3. 3hread tTne+ 3hread!<trin# name$:
4.3hread tTne+ 3hread!1unnable r, <trin# name$:
5.3hread tTne+ 3hread!3hreadOroup #, <trin# name$:
6.3hread tTne+ 3hread!3hreadOroup #, 1unnable r$:
&.3hread tTne+ 3hread!3hreadOroup #, 1unnable r, <trin# name$:
N.3hread tTne+ 3hread!3hreadOroup #, 1unnable r, <trin# name, lon# stac"siFe$:
Q1;. Cow to /et and set na*e of a Ihread?
Ans. Bor every 3hread in (ava there is a name. 3o set and #et the name of a 3hread +e can use the
follo+in# methods. All methods are final.
1./ublic final void set9ame!<trin# name$: 0 3o set the name of a 3hread
2./ublic final <trin# #et9ame!$: 0 3o #et the name of a 3hread.
Q1<. What is the ran/e of Ihread priorit+ in java?
Ans. 3he valid ran#e of a 3hread priority is 101J. !1 is least priority and 1J is hi#hest priority$
.
Q1>. Who uses Ihread priorit+?
Ans. 3hread <cheduler uses priorities +hile allocatin# ./4. 3he 3hread +hich is havin#
hi#hest priority +ill #et chance first for execution.
Q2@. What is the default priorit+ of the Ihread?
Ans. 3he default priority only for the main thread is 5 but for all remainin# threads
default priority +ill be inheritin# from parentto child. >hatever priority parent thread has the same +ill
be inherited to the child thread.
Q21. %nce we created a new Ihread what about its priorit+?
Ans. >hatever priority parent thread has the same +ill be inherited to the ne+ child thread.
Q22. Cow to /et and set priorit+ of a Ihread?
Ans. 3o #et and set priority of a 3hread, 3hread class defines the follo+in# t+o methods:
1. /ublic final int
#et/riority!$:

2. /ublic final void set/riority!int priority$:
Q20. If we are tr+in/ to set priorit+ of a Ihread as 1@@ what will happen?
Ans. If +e are tryin# to set priority of a 3hread as 1JJ then +e +ill not #et any compile time error
but at the runtime +e +ill #et 1untime exception Ille#alAr#ument-xception. ?ecause the valid ran#e
of the 3hread priority is !101J$ only.
Q23. If two threads havin/ sa*e priorit+ then which thread will /et chance first for
execution?
Ans. If t+o threads havin# same priority then +hich thread +ill #et the chance first for execution
decided by 3hread <cheduler. It is the part of *L5 and its behavior is vendor dependent and +e canAt
expect exact output.
Q27. If two threads havin/ different priorit+ then which thread will /et chance first for
execution?
Ans. If t+o threads havin# different priority then the 3hread +hich is havin# hi#hest priority +ill #et
chance first for execution.
Q29 .Cow we can prevent a thread fro* execution?
Ans. >e can prevent a 3hread from executin by usin# the follo+in# methods
1. Cield!$
2. *oin!$
3. <leep!$
Q2;. What is +ield12 *ethod? !xplain its purpose?
Ans. yield!$ method causes the current executin# thread to pause execution and #ive the chance for
+aitin# thread are same priority. If there is no +aitin# thread or all the remainin# +aitin# thread have
lo+ priority then the same thread +ill #et chance once a#ain for execution. 3he 3hread +hich is
yielded +hen it +ill #et chance once a#ain for execution depends upon mercy of 3hread
scheduler./ublic static native void yield!$:

Q2<.What is purpose of join12 *ethod?
Ans. If a 3hread +ants to +ait until some other 3hread completion then +e should #o for (oin!$
method.
-xample if a 3hread t1 execute t2.(oin!$ : then t1 +ill entered into +aitin# state until t2 3hread
completion.
Q2>. Is join12 *ethod is overloaded?
Ans. Ces (oin!$ method is overloaded method.
(ublic final void join12 throws Interrupted!xception
?y usin# this method thread +ill +ait up to another thread completion .
(ublic final void join1lon/ *s2 throws Interrupted!xception
?y usin# this method thread +ill +ail upto sometime +hat +e are passin# as a ar#ument in
millisecond
(ublic final void join1lon/ *s$ int ns2throws Interrupted!xception
?y usin# this method thread +ill +ait up to sometime +hat +e are passin# as a ar#ument in
millisecond and nanosecond.
Q0@ What is the purpose of sleep12 *ethod?
Ans. If a 3hread donAt +ant to perform any operation for a particular amount of time then +e should
#o for sleep!$ method.>henever +e are usin# sleep!$ method compulsory +e should handle
Interrupted-xception either by usin# try0catch or by usin# thro+s "ey+ord other+ise +e +ill #et
compile time error.
Q01. What is s+nchroni=ed ke+word? !xplain its advanta/es and disadvanta/es.
Ans. <ynchroniFed "ey+ord is applicable for method and bloc"s only. >e canAt use for variables
and classes.
If a method declared as a synchroniFed then at a time only one 3hread is allo+ to execute
that method on the #iven ob(ect.
3he main advanta#es of synchroniFed "ey+ord are, +e can prevent data inconsistency
problems and +e can provide 3hreadsafty.
?ut the main limitation of synchroniFed "ey+ord is it increases +aitin# time of 3hreads and
effect performance of the system. 2ence if there is no specific re)uirement it is not recommended to
use synchroniFed "ey+ord.
Q02.Where we can use s+nchroni=ed ke+word?
Ans. <ynchroniFation concept is applicable +henever multiple 3hreads are operatin# on the same
ob(ect simultaneously. ?ut +henever multiple 3hreads are operatin# on different ob(ects then there is
no impact of synchroniFation.
Q00. What is object lock? !xplain when it is reDuired?
Ans. -very ob(ect in (ava has a uni)ue loc" +henever +e are usin# synchroniFation concept then only
loc" concept +ill comin# to the picture.
If a 3hread +ants to execute a synchroniFed method first it has to #et the loc" of the ob(ect. 'nce a
3hread #ot the loc" then it is allo+ to execute any synchroniFed method on that ob(ect. After
completin# synchroniFed method execution 3hread releases the loc" automatically.>hile a 3hread
executin# synchroniFed method on the #iven ob(ect the remainin# 3hreads are not allo+ to execute
any synchroniFed method on that ob(ect simultaneously. ?ut remainin# 3hreads are allo+ to execute
any non0synchroniFed method simultaneously. !Hoc" concept is implemented based on ob(ect but not
based on method.$
Q03.What is the class level lock? !xplain its purpose.
Ans. -very class in (ava has a uni)ue loc" if a 3hread +ants to execute static synchroniFed method
that 3hread has to #et class level loc" once a 3hread #ot class level loc" then only it is allo+ to
execute static synchroniFed method.
>hile a 3hread executin# any static synchroniFed method then remainin# 3hreads are not allo+ to
execute any static synchroniFed method of the same class simultaneously. ?ut the remainin# 3hreads
are allo+ to execute the follo+in# method simultaneously
1. Any static non0synchroniFed method.
2. <ynchroniFed instance methods
3. 9on0synchroniFed instance method.
3here is no relationship bet+een ob(ect loc" and class level loc", both are independent.

Q07. While a thread executin/ an+ s+nchroni=ed *ethod on the /iven object is it possible to
execute re*ainin/ s+nchroni=ed *ethod of the sa*e object si*ultaneousl+ b+ an+ other
thread?
Ans. 9o, it is no possible.
Q09. What is the difference between s+nchroni=ed *ethod and static s+nchroni=ed *ethod?
Ans. If a 3hread +ants to execute a s+nchroni=ed *ethod first it has to #et the lock of the
object. 'nce a 3hread #ot the loc" then it is allo+ to execute any s+nchroni=ed *ethod on that
object.If a 3hread +ants to execute static s+nchroni=ed *ethod that 3hread has to #et class
level lock once a 3hread #ot class level loc" then only it is allo+ to execute static s+nchroni=ed
*ethod.
Q0;. What is the advanta/e of s+nchroni=ed block over s+nchroni=ed *ethod?
Ans. If very fe+ lines of the code re)uired synchroniFation then declarin# entire method as the
synchroniFed is not recommended. >e have to declare those fe+ lines of the code inside synchroniFed
bloc". 3his approach reduces +aitin# time of the 3hread and improves performance of the system.
Q0<. What is s+nchroni=ed state*ent?
Ans. 3he <tatement +hich is inside the synchroniFed area !synchroniFed method or synchroniFed
bloc"$ is called synchroniFed statement.
Q0>. Cow we can declare s+nchroni=ed block to /et class level lock?
Ans. 3o #et the class level loc" +e can declare synchroniFed bloc" as follo+s
synchroniFed!Display.class$
6
;
Q3@. Cow two thread will co**unicate with each other?
Ans. 3+o 3hreads +ill communicate +ith each other by usin# +ait!$, notify!$, notifyAll!$ methods.
Q31.wait12$ notif+12$ notif+All12 *ethod can available in which class?
Ans. 3hese methods are defined in 'b(ect class.
Q32.Wh+ wait12$ notif+12$ notif+All12 *ethod defines in object class instead of Ihread class?
Ans. 3hese methods are defined in 'b(ect class but not in 3hread because 3hreads are callin# this
method on the shared ob(ect.
Q30.If a waitin/ thread /ot notification then it will entered into which state?
Ans. It +ill entered into another +aitin# state to #et loc".
Q33.In which *ethod threads can release the lock?
Ans. 'nce a 3hread calls +ait!$ method it immediately releases the loc" of that ob(ect and then
entered into +aitin# state similarly after callin# notify!$ method 3hread releases the loc" but may not
immediately. -xcept these three methods! +ait!$, notify!$, notifyAll!$ $ method 3hread never releases
the loc" any+here else.
Q37. !xplain wait12$ notif+12$ notif+All12 *ethod uses.
Ans. 3+o 3hreads +ill communicate +ith each other by usin# +ait!$, notify!$ or notifyAll!$ methods.
3hese methods are defined in 'b(ect class but not in 3hread because 3hreads are callin# this
method.
Q39. What is the difference between notif+12 and notif+All12?
Ans. 3o #ive notification to the sin#le +aitin# 3hread. >e use notify!$ method and to #ive notification
to all +aitin# thread +e use notifyAll!$ method.
Q3;. %nce a Ihread /ot the notification then which waitin/ thread will /et chance?
Ans. It is depends on the 3hread <cheduler.
Q3<. Cow a thread can interrupt another thread?
Ans. A 3hread can interrupt another 3hread by usin# interrupt!$ method. Q3>. What is ,ead#ock?
Is it possible to resolve ,ead#ock situation?
Ans. If t+o 3hreads are +aitin# for each other forever such type of situation is called DeadHoc".
Bor the DeadHoc", there are no resolution techni)ues but prevention techni)ues are available.

Q7@. Which ke+word causes ,ead#ock situation?
Ans. <ynchroniFed "ey+ord is the thin# to causes of DeadHoc". If +e are not usin# properly
synchroniFed "ey+ord the pro#ram +ill entered into DeadHoc" situation.
Q71. Cow we can stop a thread explacitl+?
Ans. 3hread class defines stop!$ method by usin# this method +e can stop a 3hread. ?ut it is
deprecated. And hence not recommended to use.
Q72. !xplain about suspend12 and resu*e12 *ethod?
Ans. A 3hread can suspend another 3hread by usin# suspend!$ method.
A 3hread can resume a suspended 3hread by usin# resume!$ method.
Q70.What is "tarvation12? And !xplain the difference between ,eadlock and "tarvation?
Ans. A lon# +aitin# 3hread is said to be in starvation !because of least priority$ but after certain time
defiantly it +ill #et the chance for execution. ?ut in the case of Deadloc" t+o 3hreads +ill +ait for each
other forever. It +ill never #et the chance for execution.
Q73. What is race condition?
Ans. 5ultiple 3hreads are accessin# simultaneously and causin# data inconsistency problem is called
race condition, +e can resolve this by usin# synchroniFed "ey+ord.
Q77. What is ,ae*on Ihread? And /ive an exa*ple?
Ans. 3he 3hreads +hich are runnin# in the bac"#round are called Daemon 3hread.
-xample Oarba#e collector.
Q79. What is the purpose of a ,ae*on Ihread?
Ans. 3he main purpose of Daemon 3hreads is to provide support for non0daemon 3hreads.
Q7;. Cow we can check ,ae*on nature of a Ihread?
Ans. >e can chec" Daemon nature of a 3hread by usin# is,ae*on12 method.
Q7<. Is it possible to chan/e a ,ae*on nature of a Ihread?
Ans. Ces, +e can chan#e Daemon nature of a 3hread by usin# set,ae*on12 method.
Q7>. Is *ain thread is ,ae*on or nonJdae*on?
Ans. ?y default main thread is al+ays non0daemon nature.
Q9@. %nce we created a new thread is it dae*on or nonJdae*on.
Ans. 'nce +e created a ne+ 3hread, 3he Daemon nature +ill be inheritin# from parent to child. If
the parent is Daemon the child is also Daemon and if the parent is non0daemon then child is also non0
daemon.
Q91. After startin/ a thread is it possible to chan/e ,ae*on nature?
Ans. >e can chan#e the Daemon nature before startin# the 3hread only. 'nce 3hread started +e are
not allo+ to chan#e Daemon nature other+ise +e +ill #et 1untime-xception syin#
Ille#al3hread<tate-xception.
Q92. When the ,ae*on thread will be ter*inated?
Ans. 'nce last non0daemon 3hread terminates automatically every Daemon 3hread +ill be
terminated.
Q90. What is /reen Ihread?
Ans. A #reen thread refers to a mode of operation for the *ava Lirtual 5achine !*L5$ in +hich all
code is executed in a sin#le operatin# system thread. If the *ava pro#ram has any concurrent threads,
the *L5 mana#es multi0threadin# internally rather than usin# other operatin# system threads.
3here is a si#nificant processin# overhead for the *L5 to "eep trac" of thread states and s+ap
bet+een them, so #reen thread mode has been deprecated and removed from more recent *ava
implementations.
Q93.!xplain about Ihread /roup?
Ans. -very *ava thread is a member of a thread group. 3hread #roups provide a mechanism for
collectin# multiple threads into a sin#le ob(ect and manipulatin# those threads all at once, rather than
individually. Bor example, you can start or suspend all the threads +ithin a #roup +ith a sin#le method
call. *ava thread #roups are implemented by the 3hreadOroup api class in the (ava.lan# pac"a#e.
Q97.What is the Ihread #ocal?
Ans. It%s a +ay for each thread in multi0threaded code to "eep its o+n copy of an instance variable.
Oenerally, instance variable are shared bet+een all threads that use an ob(ect: 3hreadHocal is a +ay
for each thread to "eep its o+n copy of such a variable. 3he purpose mi#ht be that each thread "eeps
different data in that variable, or that the developer +ants to avoid the overhead of synchroniFin#
access to it.
Q99. In +our previous project where +ou used *ultithreadin/ concept?
.ollections
Q1. What are li*itations of object Arra+s?
3he main limitations of 'b(ect arrays are
3hese are fixed in siFe ie once +e created an array ob(ect there is no chance of increasin# or
decreasin# siFe based on our re)uirement. 2ence If +e donAt "no+ siFe in advance , arrays
are not recommended to use
Arrays can hold only homo#eneous elements.
3here is no underlyin# data structure for arrays and hence no readymade method support for
arrays. 2ence for every re)uirement pro#rammer has to code explicitly
3o over come these problems collections are recommended to use
Q2. What are differences between arra+s and collections?
Arra+s
Collections
1. Arrays r fixed in siFe and hence once +e
created an array +e are not allo+ed to increase or
decrease the siFe based on our re)uirement.
1. .ollections are #ro+able in nature and hence
based on our re)uirement +e can increase or
decrease the siFe.
2. 5emory point of vie+ arrays are not
recommended to use
2. 5emory point of vie+ collections are
recommended to use.
3. /erformance point of vie+ arrays are
recommended to use
3. /erformance point of vie+ collections are not
recommended to use.
4. Arrays can hold only homo#eneous elements 4. .ollections can hold both homo#eneous and
hetero#eneous elements.
5. Arrays can hold both primitives as +ell as
ob(ects
5. .ollections can hold only ob(ects.
6. Bor any re)uirement, there is no ready method
support compulsory pro#rammer has to code
explicitly.
6. Bor every re)uirement ready made method
support is available. ?ein# a pro#rammer +e have
to "no+ ho+ to use those methods and +e are not
responsible to implement those.
Q0. what are differences between arra+s and Arra+#ist?

:efer the answer of Q2
Q3. What are differences between arra+s and 8ector?

:efer the answer of Q2

Q7. What is Collection A(I ?
It defines set of classes and interfaces +hich can be used for representin# a #roup of ob(ects as sin#le
entity
Q9. What is Collection fra*ework?
It defines set of classes and inter faces +hich can be used for representin# a #roup of ob(ects as
sin#le entity
Q;. What is difference between Collections and Collection?
Collection is an interface +hich can be used for representin# a #roup of individual ob(ects as sin#le
entity and it acts as root interface of collection frame +or".
Collections is an utility class to define several utility methods for .ollection implemented class
ob(ects.
Q<. !xplain about Collection interface?
3his interface can be used to represent a #roup of ob(ects as a sin#le entity.
It acts as root interface for entire collection frame+or".
It defines the most commonly used methods +hich can be applicable for any collection
implemented class ob(ect
Q>. !xplain about #ist interface?
Hist interface is a child interface of .ollection interface. 3his can be used to represent #roup of
individual ob(ects in as a sin#le entity +here
Duplicates are allo+ed
Insertion order is preserved
Q1@. !xplain about "et interface?
<et is a child interface of .ollection interface. it can be used to represent a #roup of individual ob(ects
as a sin#le entity +here
Duplicate ob(ects are not allo+ed.
Insertion order is not preserved
Q11. !xplain about "orted"et interface?
it is child interface of <et interface. it can be used to represent a #roup of individual ob(ects in to a
sin#le entity +here
All the ob(ects are arran#ed in some sortin# order !.an be natural sortin# order or
customiFede$.
Duplicates are not allo+ed.
Q12. !xplain about 'avi/able"et ?
It is child interface of <orted<et and provides several utility methods for navi#ation purposes
It doesnAt allo+s duplicates
Insertion order is preserved
It is introduced in 1.6 version
Q10. !xplain about Queue interface?
If +e +ant to represent a #roup of individual ob(ects prior to processin#, then +e should #o for Eueue
interface. It is child interface of .ollection interface.
It has introduced in 1.5 version.
Q13. !xplain about )ap interface?
1emember it is not a child Interface of .ollection Interface and hence 5ap and .ollection Interfaces
doesnAt have any relationship.
It can be used for representin# a #roup of 'b(ects as "ey, value pairs.
?oth "eys and values should be ob(ects
Ieys can t be duplicated but values can be duplicated.
it has introduced in 1.2 version
Q17. !xplain about "orted)ap ?
If +e +ant to represent a #roup of ob(ects as "ey value pairs +here all the entries are
arran#ed accordin# some sortin# order of "eys then +e should #o for <orted5ap.
It is child interface of 5ap.
It has introduced in 1.2 version
Q19. !xplain about 'avi/able)ap?
It is child interface of <orted5ap and defines several method for navi#ation purpose
It is introduced in 1.6 version
Q1;. !xplain about Arra+#ist class?
ArrayHist is a .ollection +hich can be used to represent a #roup of ob(ects as a sin#le entity.
it is a implemented class for Hist interface
Introduced in 1.2 version
3he underlyin# data structure is resiFable or #ro+able array.
Insertion order is preserved
Duplicates are allo+ed
2etero#eneous ob(ects are allo+ed
null insertion is possible
3his class implements 1andomAccess , <erialiFable , .loneable interfaces
?est choice for retrieval purpose and +orst if our fre)uent operation is insertion or deletion in
the middle
Q1<. What is :ando*Access Interface?
If a collection class implements 1andomAccess interface then +e can access any of its element
+ith the same speed.
1andomAccess interface is mar"er interface and it dosent contains any methods.
ArrayHist and vector classes implements this interface.
Q1>. !xplain about #inked#ist class?
Hin"edHist is a .ollection implemented class +hich can be used for representin# a #roup of ob(ects as
a sin#le entity.
Hin"edHist is the implemetation class for Hist interface
Introduced in 1.2 version
4nderlyin# data <tructure is DoubleHin"edHist
Allo+s duplicates
Insertion order is preserved
Allo+s hetero#eneous ob(ects
null insertion is possible
Hin"edHist class implements <erialliFable and .loneable interface but not 1andomAccess
interface
?est choice if fre)uent operation is insertion or deletion an ob(ects in middle but +orst choice
if fre)uent operation is retrieval.
Q2@. !xplain about 8ector class?
Lector is a le#acy collection class +hich can be used to represent a #roup of ob(ects.
Introduced in 1.J version. it is le#acy class
3he underlyin# data structure is resiFable or #ro+able array.
Insertion order is preserved
Duplicates are allo+ed
2etero#eneous ob(ects are allo+ed
It is a implemented class for Hist interface
null insertion is possible
Lector class implements 1andomAccess ,<erialiFable,.loneable interfaces
?est .hoice if fre)uent operation is retrieval and +orst choice if fre)uent operation is insertion
or deletion in the middle.
All methods present in Lector class are synchroniFed hence Lector class ob(ect is thread safe.
Q21. What is difference between Arra+#ist and 8ector?

Arra+#ist
8ector
1. 9o method is synchroniFed in the ArrayHist class 1. All methods in Lector are synchroniFed.
2. ArrayHist ob(ect is not thread safe. 2. Lector is thread safe.
3. 1elatively performance is hi#h 3. 1elatively performance is lo+
4. Introduced in 1.2 version and it is non le#acy 4. Introduced in 1.J version and it is le#acy
Q22. Cow we can /et s+nchroni=ed version of Arra+#ist?
.ollections class contains synchroniFedHist!$ method for this
/ublic static Hist synchroniFedHist!Hist l$

!M
ArrayHist lT ne+ ArrayHist!$:
Hist l2T.ollections.synchroniFedHist!l$:
<imilarly +e can #et synchroniFed versions of <et and 5ap ob(ects by the follo+in# methods.
/ublic static Hist synchroniFed<et!<et s$
/ublic static Hist synchroniFed5ap!5ap m$
Q20. What is difference between si=e and capacit+ of a Collection %bject?
siFe means number of ob(ects present +here as capacity means no of ob(ects it can accommodate.
Q23. What is difference between Arra+#ist and #inked #ist?
Arra+#ist #inked#ist
1. 3he underlyin# data structure is resiFable or
#ro+able array.
1. 3he underlyin# data structure is Double Hin"ed
Hist.
2. 3his is ?est choice if fre)uent operation is
retrieval and +orst choice if fre)uent operation is
insertion or deletion in the middle.
2. 3his is ?est choice if fre)uent operation is
insertion or deletion in the middle and +orst choice
if fre)uent operation is retrieval .
3. 3his class implements <erialiFable , .loneable
and 1andomAccess interfaces.
3. 3his class implements <erialiFable , .loneable
but not 1andomAccess interface.
Q27. What are le/ac+ classes and interfaces present in Collections fra*ework ?
-numeration 000Interface
Dictonary 000000Abstract class
2ashtable 00000.oncrete class
/roperties 00000.oncrete class
Lector 00000.oncrete class
<tac" 00000.oncrete class

Q29. what is difference !nu*eration and Iterator?
!nu*eration Iterator
1. It is le#acy interface and introduced in 1.J
version
1 It is non0le#acy and introduced in 1.2 version
2Applicable only for le#acy classes and it is not
universal cursor
2Applicable for any .ollection implemented class
ob(ect.
3>hile iteratin# the elements +e are not allo+ed
to remove the ob(ects (ust +e can perform only
read operation
3>hile iteratin# +e can perform removal also in
addition to read operation.
4?y usin# elements!$ method +e can #et
-numeration ob(ect
4. ?y usin# iterator!$ method +e can #et Iterator

ob(ect
Q2;. What are li*itations of !nu*eration?
>hile iteratin# the elements +e are not allo+ed to perform removal operation
It is applicable only for le#acy classes and it is not a universal cursor.
It can retrieve the elements only in for+ard direction

Q2<. What is difference between enu* and !nu*eration?
An enu* can be used to define a #roup of named constants .It has introduced in 1.5 version
!x
Class ?eer6
I',IB,1.,B'
;
!nu*eration is cursor to retrieve 'b(ects one by one from .ollection ob(ects.
Q2>. What is difference between Iterator and #istIterator?
o HistIterator is the child interface of the Iterator
o Iterator is the sin#le direction cursor +here as HistIterator is bidirectional cursor.
o >hile iteratin# the elements by Iterator +e can perform only read and remove
operations. ?ut by usin# HistIterator +e can perform read,removal, replace and
addition of ne+ ob(ects also.
o Iterator is applicable for every .ollecton implemented class ob(ect but HistIterator is
applicable only for Hist implemented class ob(ects.
o Iterator can be #et by usin# iterator!$ of .ollection interface +here as HistIterator can
be #et by usin# listIterator!$ method of Hist interface
o both are introduced in 1.2 version
Q0@. What is relation between #istIterator and Iterator?

HistIterator is child interface of Iterator
Q01. !xplain about Cash"et class?
3he underlyin# data structure is 2ashtable
null values are accepted
duplicates are not allo+ed
insertion order is based on hashcode of the ob(ect hence insertion order is not preserved
best suitable if fre)uent operation is search operations
2ash<et class implements <erialiFable and .loneable
it is implementation class for <et interface
hetero#eneous ob(ects are allo+ed
it is introduced in 1.2 version
Q02. If we are tr+in/ to insert duplicate values in "et what will happen?
If +e are tryin# to insert duplicate ob(ects to the 2ash<et , +e +ont #et any compile time or run
time errors (ust the add!'b(ect o$ returns false and it doesnAt add that ob(ect.
Q00. What is #inkedCash"et?
It is the child class of 2ash<et. 3he main difference bet+een 2ash<et and Hin"ed2ash<et is
In the case of 2ash<et insertion order is not preserved , but in the case of Hin"ed2ash<et insertion
+ill be preserved.
Q03. ,ifferences between Cash"et and #inkedCash"et?
Cash"et #inkedCash"et
13he 4nderlyin# datastructure is 2ashtable 13he underlyin# datastructure is combination of
Hin"edHist and 2ashtable
2Insertion 'rder is not preserved 2 Insertion order is preserved.
3Introduced in 1.2 version 3 Introduced in 1.4 version

Q07. What are *ajor enhance*ents in 1.3 version of collection fra*e work?
Hin"ed2ash<et
Hin"ed2ash5ap
Identity2ash5ap

Q09. !xplain about Iree"et?

It is .ollection ob(ect +hich can be used to represent a #roup of ob(ects accordin# to some sortin#
order.
3he underlyin# datastructure is ?alanced tree
Duplicates are not allo+ed
All ob(ects are stored accordin# to some sortin# order hence insertion order is not preserved
2etero#eneous ob(ects are not allo+ed violation leads to .lass.ast-xception
Bor an -mpty 3ree<et as firs element null value can be inserted but after insertin# that first
value if +e are tryin# to insert any other ob(ects then +e +ill #et 9ull/ointer-xception
Bor an non empty 3ree<et if +e are tryin# to inser null value at run time u +ill #et
9ull/ointer-xception

Q0;. What are differences between #ist and "et interfaces?
#ist "et
1Insertion 'rder is preserved 1Insertion 'rder is not preserved
2Duplicate 'b(ects are allo+ed 2 Duplicate 'b(ects are not allo+ed
33he implemented classes
are ArrayHist,Hin"edHist , Lector and <tac" classes
3 3he implemented classes are 2ash<et,
Hin"ed2ash<et and 3ree
Q0<. What is Co*parable interface?
3his interface can be used for definin# natural sortin# order of the ob(ects.
It is present in (ava.lan# pac"a#e
It contains a method public int co*pareIo1%bject obj12
Q0>. What is Co*parator interface?
3his interface can be used for implementin# customiFed sortin# order.
It is present in (ava.util pac"a#e
It contains t+o methods
o public int co*pare!'b(ect ,'b(ect$
o public boolean eDuals!'b(ect$

Q3@. What are differences between Co*parable and Co*parator?
Co*parable Co*parator
13his can be used for natural sortin# order 13his can be used for implementin# customiFed
sortin#
23his interface present in (ava.lan# pac"a#e 2 3his is present in (ava.util pac"a#e
3.ontains only one method
public int compare3o!'b(ect ob(1$
3 It contains t+o methods.
public int compare!'b(ect ,'b(ect$
public ?oolean e)uals!'b(ect$
4 It is mar"er interface 4 It is not a mar"er interface.
Q31. What is difference between Cash"et and Iree"et?
Cash"et Iree"et
13he underlyin# data structure is 2ashtable 13he underlyin# data structure is balanced tree
22etero#eneous ob(ects are allo+ed 2 2etero#eneous ob(ects are not allo+ed
bydefalut
3Insertion order is not preserved and it is based on
hashcode of the ob(ects
3 Insertion order is not preserved and all the
ob(ects are inserted accordin# to some sortin#
order.
4null insertion is possible 4 As the first element only null insertion is
possible and in all other cases +e +ill #et
9ull/ointer-xception
Q32. What is !ntr+ interface?
It is inner interface of 5ap.
In the 5ap each "ey value pair is considered as -ntry ob(ect.

interface )apN
BB*ore code here
interface !ntr+N
%bject /etFe+12
%bject /et8alue12
%bject set8alue1%bject new2
O
O
Q30. !xplain about Cash)ap?
It is a )ap %bject which can be used used to represent a /roup of objects as ke+Jvalue
pairs.
3he underlyin# data structure is 2ashtable
Duplicaes "eys are not allo+ed duplicate values are allo+ed
Insertion order is not preserved because insertion is based on hashcode of "eys.
2etero#eneous ob(ects are allo+ed for both "eys and values
null "ey is allo+ed only once
null values are allo+ed multiple times
Introduced in 1.2 version
Q33. !xplain about #inkedCash)ap?
It is child class of 2ash5ap. It is exactly same as 2ash5ap except the follo+in# difference.
In the case of 2ash5ap the insertion order is not preserved but in the case of Hin"ed2ash5ap
insertion order is preserved. Introduced in 1.4 version
Q37. ,ifferences between Cash)ap and #inkedCash)ap ?
Cash)ap #inkedCash)ap
1.3he underlyin# data structure is 2ashtable 1.3he underlyin# data structure is a combination of
2ashtable and lin"edlist
2.Insertion order is not preserved and it is based
on hashcode of "eys
2 Insertion order is preserved
3.Introduced in 1.2 version 3 Introduced in 1.4 version.
Q39. ,ifferences between Cash)ap and Cashtable?
Cash)ap Cashtable
1.3he underlyin# data structure is 2ashtable 1.3he underlyin# data structure of 2ashtable
2.9o method is synchroniFed and hence 2ash5ap
ob(ect is not thread safe
2 .All methods are synchroniFed and hence it is
thread safe
3./erformance is hi#h 3. /erformance is lo+
4.null insertion is possible for both "eys and values 4. null insertion is not possible for both "ey and
value violation leads to 9ull/ointer-xception
5.Introduced in 1.2 version and it is non le#acy 5. Introduced in 1.J version and it is le#acy

Q3;. What is Identit+Cash)ap?
It is exactly same as 2ash5ap except the follo+in# difference.
In the 2ash5ap *L5 uses e)uals!$ method to identify duplicate "eys but in the case of
Identity2ash5ap *L5 uses TT operator for this.

Q3<. What is difference between Cash)ap and Identit+Cash)ap?

1efer E4& for the ans+er.
Q3>. What is WeakCash)ap?

It is exactly same as 2ash5ap except the follo+in# difference.
In case of 2ash5ap an 'b(ect is not eli#ible for #arba#e collection if it is associated +ith 2ash5ap
even thou#h it dosent have any external references. ie 2ash5ap dominates #arba#e collector.
?ut in case of >ea"2ash5ap , if an 'b(ect is not havin# any external references then it is al+ays
eli#ible for #araba#e collectoion even thou#h it is associated +ith +ea"2ash5ap. ie
#arba#e collector dominates >ea"2ash5ap
Q7@. What is difference between Cash)ap and WeakCash)ap?
1efer E4K for the ans+er.
Q71. What is Iree)ap?
3ree5ap can be used to store a #roup of ob(ects as "ey0value pairs +here all the entries are arran#ed
accordin# to some sortin# order of "eys.
3he underlyin# data structure is 1-D0?HA.I 3ree
Duplicates "eys are not allo+ed but values can be duplicated.
Insertion order is not preserved because insertion is based on some sortin# order
If +e are dependin# on 9atural sortin# order then "eys should be homo#eneous!violation
leads to .lass.ast-xception$ but values need not homo#eneous
In case of customiFed sortin# order +e can insert hetero#eneous "eys and values
Bor empty 3ree5ap as first entry +ith null values are allo+ed but after insertin# that entry if
+e are tryin# to insert any other entry +e +ill #et 9ull/ointer-xception
Bor non empty 3ree5ap if +e are tryin# to insert null "eys +e +ill #et 9ull/ointer-xception
3here are no restrictions for null values.

Q72. What is Cashtable

2ashtable is a le#acy 5ap and can be used to store ob(ects as "ey value pairs.
3he underlyin# data sturucture is 2ashtabe
Duplicates "eys are not allo+ed but duplicate values are allo+ed
null insertion is not possible for both "eys and values
all methods are synchroniFed
insertion order is not preserved because it is based on hashcode of "eys
hetero#eneous 'b(ects are allo+ed for both "eys and values
introduced in 1.J version it is le#acy class
Q70. What is (riorit+Queue?
It represents a data structure to hold #roup of individual ob(ects prior to processin# based on some
priority .it can be natural sortin# order and it can be customiFed sortin# order described by
.omparator.
It is the implementation class of Eueue interface.
Insertion order is not preserved because here insertion is done based on some sortin# order
Duplicates are not allo+ed
null insertion is not possible even as first element also
If +e are dependin# on natural sortin# order 'b(ects should be homo#eneous violation leads
to .lass.ast-xception
If +e are dependin# on customiFed sortin# order 'b(ects can be hetero#eneous also.
Q73. What is Arra+s class?
It is utility class for arrays.
It defines several utility methods for arrays li"e sortin# an array or searchin# an element in
array
present in (ava.util pac"a#e
Q77. We are plannin/ to do an indexed search in a list of objects. Which of the two 6ava
collections should +ou useArra+#ist or #inked#ist?
ArrayHist
Q79. Wh+ Arra+#ist is faster than 8ector?
All methods present in the Lector are synchroniFed and hence any method can be executed by only
one thread at a time. It slo+s do+n the execution.
?ut in ArrayHist, no method is synchroniFed and hence multiple thread are allo+ed execute
simultaneously +hich speed up the execution.
*dbc
1: What is the difference between ,atabase and ,atabase *ana/e*ent s+ste*?
Ans: Database is a collection of interrelated data. Database mana#ement system is a soft+are
+hich can be used to mana#e the data by storin# it on to the data base and by retrievin# it from
the data base. And D?5< is a collection of interrelated data and some set of pro#rams to access the
data.
3here are 3 types of Database 5ana#ement <ystems .
1elational Data?ase 5ana#ement <ystems!1D?5<$ It is a soft+are system, +hich can be
used to represents data in the form of tables. 1D?5< +ill use <EH2 as a Eueries lan#ua#e.
'b(ect 'riented Data?ase 5ana#ement <ystems!''D?5<$ It is a soft+are system, +hich
can be used to represent the data in the form of ob(ects. 3his D?5< +ill use 'EH as a Euery
lan#ua#e.
'b(ect 1elational Data?ase 5ana#ement <ystems!'1D?5<$ It is a D?5< +hich +ill
represents some part of the data in the form of tables and some other part of the data in the
form of ob(ects. 3his mana#ement system +ill use <EH3 as a Euery Han#ua#e, it is a
combination of <EH2 and 'EH.
2: How a query could be executed when we send a query to Database?
>hen +e send an <EH Euery from <EH prompt to the Data?ase-n#ine, then Database -n#ine +ill ta"e
the follo+in# steps.
Euery 3o"eniFation 3his phase +ill ta"e <EH )uery as an input and devide into stream of
to"ens.
Euery /arsin# 3his phase +ill ta"e stream of to"ens as an input, +ith them it tried to
construct a )uery tree. If )uery parser constructs )uery tree successfully then it +as an
indication that no #rammatical mista"es in the ta"en <EH )uery. 'ther+ise there are some
syntactical errors in the ta"en <EH )uery.
Euery 'ptimiFation 3his phase +ill ta"e )uery tree as an input and performs number of
)uery optimiFation mechanisms to reduce execution time and memory utiliFation.
Euery -xecution 3his phase +ill ta"e optimiFed )uery as an input and executes that <EH
)uery by usin# interpreters internally as a result +e +ill #et some output on the <EH prompt.
3: What is Driver? How many Drivers are available in JD!? What are the ty"es?
It is a process of interactin# +ith the database from a (ava application .
In *D?. applications +e must specify the complete database lo#ic in (ava application as for
the (ava A/I representations, later on +e need to send (ava represented database lo#ic to the
database en#ine!D?-$.
D?- must execute the database lo#ic but it +as confi#ured as per the (ava representations but
D?- able to understand only Euery Han#ua#e representations.
At the above situation if +e +ant to execute our database lo#ic, +e need to use one interface
in bet+een (ava applicationand the database, that interface must convert (ava representations
to )uery lan#ua#e representations and )uery lan#ua#e representations to (ava
representations. 9o+ this interface is called as a ZDriver[.
,river
It is a soft+are or an interface existed in bet+een a (ava application and database, +hich +ill
map (ava api calls +ith )uery lan#ua#e api calls and vice versa.
Initially sun 5icrosystems has provided Zdriver interface[ to the mar"et +ith this
sun 5icrosystems has #iven an intimation to all the database vendors to have their o+n
implementation as per their re)uirements for the Driver interface.
As a response all the database vendors are providin# their o+n implementation for the Driver
interface inorder to interact +ith the respective databases from a (ava application.
3he users of the respective databases they must #et the respective database provided Driver
implementation from the database soft+are and ma"e use as part of the *D?. applications to
interact +ith the respective databases form a (avaapplication.
I+pes of ,rivers
3here are 1NJ@ number of Drivers in the mar"et. ?ut all these Drivers could be classified into
the follo+in# 4 types.
3ype 1 Driver
3ype 2 Driver
3ype 3 Driver
3ype 4 Driver
I+pe 1 ,river
o 3ype 1 Driver is also called as *dbc0'dbc Driver or ?rid#e Driver.
o *dbc0'dbc Driver is an implementation to Driver interface provided by the
sun 5icrosystems alon# +ith the (ava soft+are.
o *dbc0'dbc Driver internally depends on the 5icrosoft product 'dbc Driver.
o 'dbc is nothin# but open database connectivity. It is a open specification +hich can be
used to interact +ith any type of databases.
Advanta/es
3his Driver is already available +ith (ava soft+are thatAs +hy no need to bother about ho+ to
#et the Driver implementation explicitily.
Allmost all the databases could support this Driver.
,is advanta/es
3his Driver internally depends on 'dbc Driver thatAs +hy it is not suitable for internet or
+eb applications or net+or"applications.
3his Driver is a slo+er Driver, +hy because *dbc0'dbc Driver +ill convert (ava calls to 'dbc
calls. 3hen 'dbc Driver has to convert 'dbc calls to )uery lan#ua#e calls.
3his driver is not portable Driver +hy because it +as not complete the (ava implementations in
*dbc0'dbc Driver.
It +e +ant to use *dbc0'dbc Driver in our (dbc applications then +e must re)uire to install
'dbc09ative Hibrary.
I+pe 2 ,river
3ype 2 Driver is also called as Zpart (ava part native Driver[. i.e., this Driver +as desi#ned by
usin# some part of the (ava implementations and some other part of the database vendor provided
native implementations. 3his Driver is also called as Znative driver[.
Advanta/es
>hen compared to 3ype 1 driver it is efficient driver +hy because 3ype 2 driver directly +ill
convert (ava api calls to database vendor api calls.
,is advanta/es
If +e +ant to use 3ype 2 Driver in our *dbc applications then +e must re)uire to install
database vendor native api.
It is a costful Driver.
It is not suitable for +eb applicadtions, distributed applications and +eb applications.
3ype 2 Driver performance is lo+ +hen compared to 3ype 3 and 3ype 4 drivers.
3his driver is not portable driver. >hy because this driver +as not desi#ned completely in (ava
technolo#y.
I+pe 0 ,river
o It is also called as middle+are database access server driver.
o 3his driver could be used to interact +ith multiple databases from the multiple clients.
o 3his driver could be used in collaboration +ith application server.
o 3his driver is su##estable for net+or" applications.
Advanta/es
It is a fastest driver amon# all the drivers available in the mar"et.
3o use 3ype 3 driver in our (dbc applications it is not re)uired to install odbc native library and
database native library.
It is very much suitable for net+or" applications.
,is advanta/es
3his driver is not suitable for simple (dbc applications.
3his driver re)uires minimum 303ier Architecture.
>hen compared to 3ype1 and 3ype2 drivers.. 3ype3 driver is efficient and portable. ?ut +hen
compared to 3ype4 driver, 3ype3 driver is not portable.
I+pe 3 ,river
o 3his driver is also called as pure (ava driver i.e, this driver +as completely
implemented by usin# (ava technolo#y.
o >hen compared to 3ype1, 3ype2 and 3ype3 drivers.. 3ype4 driver is portable driver.
o 3ype4 driver can be used for any "ind of applications.
o 3ype4 driver is a cheapest driver +hen compared to all the drivers thatAs +hy it is
fre)uently used driver.
#: What is JD! and What are the ste"s to write a JD! a""lication?

3he process of interactin# +ith the database from a (ava application is called as *D?.!*ava Database
.onnectivity$
3o interact +ith the database from a (ava application +e +ill use the follo+in# five steps.
1. load and re#ister the driver.
2. -stablish a connection bet+een (ava application and the database.
3. prepare either statement ob(ect or /repared<tatement ob(ect or .alleble<tatement ob(ect as
per the applicationre)uirements.
4. +rite and executer the s)l )ueries.
5. terminate the connection +hich +e have established.
$: How to load a JD! driver?
o In #eneral sun 5icrosystems has provided Driver interface for this all the database
vendors has provided their o+n implementation.
o If +e +ant to use the database vendor provided Driver implementation to our
(dbc application, first +e need to ma"e the availability of the respective DriverAs
.class file to *L5, for this +e need to set class path environment variable to the
location +here +e have the driver implementation.
o <un 5icrosystems is also provided an implementation to the Driver interface in the
form of *dbc'dbcDriver class as part of the (ava soft+are.
o If +e +ant to use *dbc'dbcDriver in our (dbc applications no need to set class path
environment variable. >hy because it +as already available in the (ava soft+areAs pre0
defined library.
o *dbc'dbcDriver internally depends on the mocrosoft product 'dbc driver. If +e +ant
to use the *dbc'dbcDriver in our (dbc applications first +e must confi#ure 'dbc driver,
for this +e +ill use the follo+in# path.
<tart7 conrlol panel 7 performance and maintenance 7 administrative tools 7 data source!'dbc$7 user
dsn 7 clic" on Add 7 select microsofr 'dbc for oracle 7 finish 7 provide data source name only 7 clic" on
o" 7 o".
3o load the driverAs class byte code to the memory +e +ill use the follo+in# method.
/ublic void for9ame!<trin# class name$
!/ .lass.for9ame!Zsun.(dbc.odbc.*dbc'dbcDriver[$:
>here for9ame!$ is a static method, +hich can be used to load the respective driver class byte
code to the memory.
-ach and every driver class has already a static bloc" at the time of loadin# the respective
driver class byte code to the memory automatically the available static bloc" could be
executed, by this Driver5ana#er.re#isterDriver!_.$ method +ill be executed as part of the
static bloc".
?y the execution of the re#isterDriver!_.$ method automatically the specified driver +ill be
re#ister to the (dbc application.
If you +ant to desi#n any (dbc application, +e need to use some pre0defined library, +hich
+as provided by the *dbc A/I in the form of (ava.s)l pac"a#e, thatAs +hy +e need to import
(ava.s)l pac"a#e in our (dbc application.
'oteJ 3he best alternative for .lass.for9ame!..$ is
Driver5ana#re.re#isterDriver!ne+ sun.(dbc.odbc.*dbc'dbcDriver!$$:
3o re#ister the driver.
%: How to establish a Database connection between &ava a""lication and Database?
If +e +ant to establish a connection bet+een (ava application and the database +e +ill the follo+in#
piece of code.
Connection conK
,river)ana/er./etConnection1Pjdbcodbcna/Q$Qna/Q$Qs+ste*Q$Q*ana/erQ2R
>here #et.onnectin!$ is a static method from Driver5ana#er class, +hich can be used to return
connection ob(ect.
': -asicall+ Connection is an interface$ how /etConnection12 will create an object for
Connection interface?
Ans: .onnection is an interface from (ava.s)l pac"a#e, for +hich #et.onnection!X$ +as return an
anonymous inner class ob(ect of the .onnection interface.
'oteJ Anonymous inner class is a nameless inner class, +hich can be sued to provide an
implementation either for the interfaces or for abstract classes.
!/ interface I
N
void m1!$:
O
.lass 'uter
N
I i T ne+ I!$N
public void m1!$
N

O
public void m2!$
N
O
O
O
'uter o T ne+ 'uter!$:
o.i.m1!$: ` correct
o.i.m2!$: ` +ron#
#et.onnection!X$ is a static method from Driver5ana#er class, +hich +ill call
internally connect!$ method, this connect!$ +ill establish a virtual soc"et connection in bet+een the
(ava application and the database.
(: What is the requirement to use )tatement ob&ect?
After establishin# a connection bet+een (ava application and the database +e need to +rite
the s)l )ueries and +e need to execute them.
3o execute the s)l )ueries +e +ill use some pre0defined library, +hich +as defined in the form
of <tatement ob(ect, /repared<tattement ob(ect and .allable<tatement ob(ect.
As per the application re)uirements +e need to create either <tatement ob(ect or
.allable<tatement ob(ect and /repared<tatement ob(ect.
3o create <tatement ob(ect d+e +ill use the follo+in# method from connection ob(ect.
public <tatement create<tatement!$
!/ <tatement st T con.create<tatement!$:
K: How to execute )*+ *ueries ,rom a &ava a""lication?
3o execute the s)l )ueries +e +ill use the follo+in# methods from <tatement ob(ect.
st.executeEuery!_$
st.execute4pdate!_$
st.execute!_$
1-: What are the di,,erences between execute*uery./01 execute2"date./0 and
execute./0
methods?
Ans +here executeEuery!$ can be used to execute selection #roup s)l )ueries to fetch the data
from database.
>hen +e use selection #roup s)l )uery +ith executeEuery!$ then *L5 +ill send that s)l )uery to the
database en#ine, database en#ine +ill execute it, by this database en#ine!D?-$ +ill fetch the data
from database and send bac" to the (ava application.
*ava is a purely ob(ect oriented technolo#y. 3hatAs +hy the (dbc application +ill maintain the fetched
data from database, in the form of an ob(ect at heap memory, called as 1esult<et ob(ect.
public :esult"et executeQuer+1"trin/ sDlDuer+2
+here execute4pdate!$ can be used to execute updation #roup s)l )uery to update the
database. >hen +e provide updation #roup s)l )uery as a parameter to execute4pdate!$, then *L5
+ill send that s)l )uery to D?-, here D?- +ill execute it and perform updations on the database, by
this D?- +ill identify the number of records #ot updated value called as Zrecords updated count[ and
return bac" to the (ava application.
public int execute&pdate1"trin/ sDlDuer+2
+here execute!$ can be used to execute either selection #roup s)l )ueries or updation #roup
)ueries.
>hen +e use selection #roup s)l )uery +ith the execute!$ then +e +ill #et 1esult<et ob(ect at
heap memory +ith the fetched data. ?ut execute!$ +ill return Ztrue[ as a ?oolean value.
>hen +e use updation #roup s)l )uery +ith execute!$ then +e +ill #et Z records updated
count value[ at (dbc application. ?ut execute!$ +ill return Zfalse[ as a ?oolean value.
public boolean execute1"trin/ sDlDuer+2
11: How to create a table dynamically ,rom a &dbc a""lication?3
77import section
import (ava.s)l.8:
import (ava.io.8:
public class .reate3able-x
6
public static void main!<trin#RS ar#s$thro+s -xception
6
77create buffered reader ob(ect
?uffered1eader br T ne+ ?uffered1eader!ne+ Input<tream1eader!<ystem.in$$:
77load and re#ister the driver
.lass.for9ame!Zsun.(dbc.odbc.*dbc'dbcDriver[$:
77establish connection
.onnection con T Driver5ana#er.#et.onnection!Z(dbcodbcna#[,[system[,[dur#a[$:
77create statement ob(ect
<tatement st T con.create<tatement!$:
77ta"e table name as dynamic input
<ystem.out.println!Z-nter table name[$:
<trin# tname T br.readHine!$:
77execute s)l )uery
<t.execute4pdate!Zcreate table[@tname@[!eno number,ename varchar2!1J$,esal
number,eaddr varchar2!1J$$[$:
<ystem.out.println!Ztable created successfully[$:
77closin# the connection
con.close!$:
;
;
12: How to insert records into a table ,rom a JD! a""lication?
import (ava.s)l.8:
import (ava.io.8:
public class Insert3able-x
6
public static void main!<trin#RS ar#s$ thro+s -xception
6
?uffered1eader br T ne+ ?uffered1eader!ne+ Input<tream1eader!<ystem.in$$:
.lass.for9ame!Zoracle.(dbc.driver.'racleDriver[$:
.onnection con T
Driver5ana#er.#et.onnection!Z(dbcoraclethinalocalhost1521xe[,[system[,[dur#a[$:
<tatement st T con.create<tatement!$:
+hile!true$
6
<ystem.out.println!Z-nter emp number[$:
Int eno T Inte#er.parseInt!br.readHine!$$:
<ystem.out.println!Z-nter emp name[$:
<trin# ename T br.readHine!$:
<ystem.out.println!Z-nter emp sal[$:
Bloat esal T Bloat.parseBloat!br.readHine!$$:
<ystem.out.println!Z-nter emp address[$:
<trin# eaddr T br.readHine!$:
st.execute4pdate!Zinsert into emp1 values!Z@eno@[,A[@ename@[A,[@esal@[,A[@eaddr@[A$[$:
<ystem.out.println!Zread successfully inserted[$:
<ystem.out.println!Zone more recordRy7nS$:
<trin# option T br.readHine!$:
If!option.e)uals!Zn[$$
brea":
;
;
;
13: How to u"date a table ,rom a &dbc a""lication?3
import (ava.s)l.8:
public class 4pdate3able-x
6
public static void main!<trin#RS ar#s$thro+s -xception
6
77load n re#ister the driver in alternative +ay to .lass.for9ame
Driver5ana#er.re#isterDriver!ne+ oracle.(dbc.driver.'racleDriver!$$:
.onnection con T
Driver5ana#er.#et.onnection!Z(dbcoraclethinalocalhost1521xee[,[system[,[dur#a[$:
<tatement st T con.create<tatement!$:
int update.ount T st.execute4pdate!Zupdate emp1 set esal T esal@5JJ +here esal\KJJJ[$:
<ystem.out.println!Zrecords updated__..[@update.ount$:
con.close!$:
;
;
1#: How to delete records ,rom a table ,rom &dbc a""lication?3
import (ava.s)l.8:
public class Delete3able-x
6
public static void main!<trin#RS ar#s$thro+s -xception
6
.lass.for9ame!Zoracle.(dbc.driver.'racleDriver[$:
.onnection con T
Driver5ana#er.#et.onnection!Z(dbcoraclethinalocalhost1521xe[,[system[,[dur#a[$:
<tatement st T con.create<tatement!$:
int update.ount T sst.execute4pdate!Zdelete from emp3 +here esalMT&JJJ[$:
<ystem.out.println!Zrecords deleted___[@update.ount$:
con.close!$:
;
;

1$:What is ment by 4esult)et ob&ect and How to 5etch the Data ,rom Database?3
4esult)et:6
1esult<et is an 'b(ect +hich can be used to maintain the fetched data from database in the *D?.
applications

>hen +e execute a selection #roup s)l )uery, either +ith executeEuety!$ or +ith execute!$
automatically a 1esult<et ob(ect +ill be created at heap memory +ith the fetched data from database.
3o #et the 1esult<et ob(ect reference directly +e +ill use executeEuery!..$.
>hen +e create a 1esult<et ob(ect automatically a cursor +ill be create called as Z1esult<et
cursor[ to read the data from 1esult<et ob(ect.
>hen +e create the 1esult<et ob(ect by default 1esult<et cursor +ill be created before the
first record.
If +e +ant to read the data from 1esult<et ob(ect every time +e need to chec" +hether the
next record is available or not. If the next record is available automatically +e need to move
that 1esult<et cursor to next record position.
3o perform this +or" +e +ill use the follo+in# method from 1esult<et interface.
public boolean next!$
After #ettin# 1esult<et cursor to a record position then +e need to #et the data from
respective fields of the particularrecord, for this +e +ill use follo+in# method.

public xxx #et^xx!int fno$
!or$
public xxx #et^xx!<trin# fname$
+here xxx is byte, shor, int, lon#, float, double, char.
!/ +hile!rs.next!$$
N
<ystem.out.println!rs.#etInt!1$@[ [@rs.#et<trin#!2$@[ [@rs.#etBloat!3$@[ [@rs.#et<trin#!4$$:
O

Ihe followin/ exa*ple de*onstrates how to fetch the data fro* database throu/h
:esult"et object.
import (ava.s)l.8:
public class Betch-x
6
public static void main!<trin#RS ar#s$thro+s -xception
6
.lass.for9ame!Zsun.(dbc.odbc.*dbc'dbcDriver[$:
.onnection con T Driver5ana#er.#et.onnection!Z(dbcodbcna#[,[system[,[dur#a[$:
<tatement st T con.create<tatement!$:
1esult<et rs T st.executeEuery!Zselect 8 from emp1[$:
<ystem.out.println!Z-9' -9A5- -<AH -ADD1[$:
<ystem.out.println!Z88888888888888888888888888888888[$:
+hile!rs.next!$$
6
<ystem.out.println!rs.#etInt!1$@[[@rs.#et<trin#!2$@[ [@rs.#etBloat!3$@[
[@rs.#et<trin#!4$$:
;
;
;
1%:7n8eneral execute.0 method can be used to execute selection 8rou" )*l queries ,or
8ettin8 the data ,rom Database 1 but execute.0 return a boolean value true so here how it
"ossible to ,etch the data ,rom database?
-xecute!$ can be used to execute both selection #roup s)l )uery and updation #roup s)l
)uery.
If +e use execute!$ to execute a selection #roup s)l )uery then D?-!Database en#ine$ +ill
execute that s)l )uery and send bac" the fetched data from database to (ava application.
9o+ (ava application +ill prepare a 1esult<et ob(ect +ith the fetched data but execute!$ +ill
return Ztrue[ as a ?oolean value.
At this situation to #et the reference of the 1esult<et ob(ect explicitily, +e +ill use the
follo+in# method from <tatement ob(ect.
public 1esult<et #et1esult<et!$
!/ boolean b T st.execute!Zselect 8 from emp1[$:
<ystem.out.println!b$:
1esult<et rs T st.#et1esult<et!$:
1':7n8eneral execute.0 method can be used to execute u"datation 8rou" )*l queries ,or
u"datin8 the data on Database 1 but execute.0 return a boolean value ,alse so here how it
"ossible to 8et the records u"dated count value.int value0?
-xecute!$ can be used to execute both selection #roup s)l )ueries and updation #roup s)l
)ueries.

If +e use execute!$ to execute an updation #roup s)l )uery then D?- +ill execute it and send
bac" the records updated count value to the (ava application. ?ut execute!$ +ill return Zfalse[
as a ?oolean value. At this instance, to #et the records updated count value explicitly +e +ill
use the follo+in# method from <tatement ob(ect.
public int #et4pdate.ount!$
!/ import (ava.s)l.8:
public class Betch-x
6
public static void main!<trin#RS ar#s$thro+s -xception
6
.lass.for9ame!Zsun.(dbc.odbc.*dbc'dbcDriver[$:
.onnection con T Driver5ana#er.#et.onnection!Z(dbcodbcna#[,[system[,[dur#a[$:
<tatement st T con.create<tatement!$:
boolean b T st.execute!Zupdate emp1 set esalTesal@5JJ +here esal\KJJJ[$:
<ystem.out.println!b$:
int update.ount T st.#et4pdate.ount!$:(
<ystem.out.println!update.ount$:
;
;
1(: 7, we use selection 8rou" )*+ query to execute2"date.0 1what ha""ened?
If +e use selection #roup s)l )uery as a parameter to execute4pdate!_$ then *L5 +ill send
that s)l )uery to the D?-, D?- +ill fetch the data and send bac" to the (ava application here
(ava application +ill store the fetched data in the form of 1esult<et ob(ect. ?ut
execute4pdate!$ is expectin# records updated count value.
Due to this contradiction *L5 +ill rise an exception li"e (ava.lan#.<EH-xception.
If +e handle the above exception properly then +e +ill #et 1esult<et ab(ect and +e +ill #et the data
from Database
import (ava.s)l.8:
class 3est
6
public static void main!<trin#RS ar#s$
6
<tatement stTnull:
try
6
.lass.for9ame!Zsun.(dbc.odbc.*dbc'dbcDriver[$:
.onnection con T Driver5ana#er.#et.onnection!Z(dbcodbcna#[,[system[,[dur#a[$:
st T con.create<tatement!$:
boolean b T st.execute4pdate!Zselect 8 from emp1[$:
;
catch!-xception e$
6
1esult<et rsTst.#et1esult<et!$:
<ystem.out.println!Z-9' -9A5- -<AH -ADD1[$:
<ystem.out.println!Z88888888888888888888888888888888[$:
+hile!rs.next!$$
6
<ystem.out.println!rs.#etInt!1$@[[@rs.#et<trin#!2$@[ [@rs.#etBloat!3$@[
[@rs.#et<trin#!4$$:
;
e.print<tac"3race!$:
;
;
19: 7, we use u"datation 8rou" )*+ query to execute*uery.0 1what ha""ened?
If +e use updation #roup s)l )uery as a parameter to executeEuery!$ then *L5 +ill send that
s)l )uery to the D?-, D?- +ill perform updations on the database and send bac" records
updated count value to the (ava application. ?ut here executeEuery!$ is expectin# 1esult<et
ob(ect reference.
Due to this contradiction *L5 +ill rise an exception li"e (ava.lan#.<EH-xception.

import (ava.s)l.8:
class 3est
6
public static void main!<trin#RS ar#s$
6
<tatement stTnull:
try
6
.lass.for9ame!Zsun.(dbc.odbc.*dbc'dbcDriver[$:
Driver5ana#er.#et.onnection!Z(dbcodbcna#[,[system[,[dur#a[$:
st T con.create<tatement!$:
boolean b T st.executeEuery!Zupdate emp1 set esalTesal@1JJJ +here esal \1JJJJ[$:
;
catch!-xception e$
6
int countTst.#et4pdate.ount!$:
<ystem.out.println!count$:
e.print<tac"3race!$:
;
;
2-: What is ment by 4esult)et and What are the ty"es o, 4esult)ets are available in JD!
a""lication?

In (dbc applications 1esult<ets could be classified in the follo+in# t+o +ays.
%n the basis of :esult"et privili=ations 1Concuranc+2J

3here are 2 types of 1esult<ets.
o 1ead only 1esult<et
o 4pdatable 1esult<et
1ead only 1esult<et0 It is a 1esult<et, +hich +ill allo+ the users to read the data only. 3o refer
this 1esult<et, +e +ill use the follo+in# constant from 1esult<et interface.
public static final int .'9.41X1-ADX'9HC:
4pdatable 1esult<et0 If is a 1esult<et ob(ect, +hich +ill allo+ users to perform some updations on
its content. 3o refer this 1esult<et +e +ill use the follo+in# constant from 1esult<et interface.
public static final int .'9.41X4/DA3A?H-:
22%n the basis of the :esult"et cursor *ove*entJ
3here are 2 types of 1esult<ets.
o Bor+ard only 1esult<et
o <crollable 1esult<et
Bor+ard only 1esult<et0 It is a 1esult<et ob(ect, +hich +ill allo+ the users to iterate the data in any
for+ard direction. 3o refer this 1esult<et ob(ect +e +ill use the follo+in# constant from 1esult<et
interface.
public static final int 3C/-XB'1>A1DX'9HC:
<crollable 1esult<et0 3hese are the 1esult<et ob(ects, +hich +ill allo+ the users to iterate the data in
both for+ard and bac"+ard directions.
3here are 2 types of <crollable 1esult<ets.
<croll sensitive 1esult<ets
<croll in sensitive 1esult<ets.
21: What is the difference between "croll"ensitive :esult"et and "crollInsensitive
:esult"ets?
Ans <croll sensitive 1esult<et is a 1esult<et ob(ect, +hich +ill allo+ the later updations from
database automatically after creatin# it. 3o refer this 1esult<et +e +ill use the follo+in# constant.
public static final int 3C/-X<.1'HHX<-9<I3IL-:
<croll insensitive 1esult<et is a 1esult<et ob(ect, +hich +ill not allo+ later updations from
database after creatin# it. 3o refer this 1esult<et +e +ill use the follo+in# constant from 1esult<et
interface.
public static final int 3C/-X<.1'HHXI9<-9<I3IL-:
22:What is the de,ault 4esult)et ty"e in JD! a""lication and How it is "ossible to create a
s"eci,ic ty"e o, 4esult)et ob&ect?
3he default 1esult<et type in the (dbc applications is 1ead only and for+ard only.
In (dbc applications +e are able to specify the follo+in# types of the 1esult<et combination to
any particular 1esult<et.

o read0only, for+ard only
o read0only, scroll sensitive
o read0only, scroll insensitive
o updatable, for+ard only
o updatable, scroll sensitive
o updatable, scroll insensitive
if +e +ant to specity a particular type to the 1esult<et ob(ect then +e should use either of the
above constants combination as a parameter to create<tatement!$ method, for this +e +ill
use the follo+in# method.

public <tatement create<tatement!int for+ard 7 <croll<ensitive 7 <crollInsensitive, int readonly 7
updatable$
!/ <tatement st T con. create<ensitive!1esult<et.3C/-X<.1'HHX<-9<I3IL-,
1esult<et..'9.41X4/DA3A?H-$:
1esult<et rs T con.executeEuery!_.$:

23:How to iterate the data ,rom )crollable 4esult)et ob&uect in both ,orward and bac:word
direction?
to iterate the data in for+ard direction from a 1esult<et ob(ect +e +ill use the follo+in# 2
methods.
public ?oolean next!$
public xxx #et^xx!int fieldno.$
>here xxx may be byte, short, char, int, lon#, float, double.
3o iterate the data in bac"+ard direction from <crollable 1esult<et ob(ect +e +ill use the
follo+in# 2 methods.

public ?oolean previous!$
public xxx #et^xx!int fieldno$
>here previous!$ is a ?oolean method, +hich can be used to chec" +hether the previous
record is available or not, if it is available then cursor +ill be moved to previous record position.

Ihe followin/ exa*ple de*onstrates how to iterate the data in both forward and backward
direction fro* the :esult"et object
import (ava.s)l.8:
public class <croll1es-x
6
public static void main!<trin#RS ar#s$thro+s -xception
6
.lass.for9ame!Zsun.(dbc.odbc.*dbc'dbcDriver[$:
.onnection con T Driver5ana#er.#et.onnection!Z(dbcodbcna#[,[system[,[dur#a[$:
<tatement st T
con.create<tatement!1esult<et.3C/-X<.1'HHX<-9<-I3IL-,1esult<et..'9.41X4/DA3A?H-$:
1esult<et rs T st.executeEuery!Zselect 8 from emp1[$:
<ystem.out.println!Zdata in for+ard direction[$:
<ystem.out.println!Z-9' -9A5- -<AH -ADD1[$:
<ystem.out.println!Z8888888888888888888888888888888888[$:
>hile!rs.next!$$
6
<ystem.out.println!rs.#etInt!1$@[ [@rs.#et<trin#!2$@[ [@rs.#etBloat!3$@[ [@rs.#et<trin#!4$$:
;
<ystem.in.read!$:
<ystem.out.println!Zdata in bac"+ard direction[$:
<ystem.out.println!Z-9' -9A5- -<AH -ADD1[$:
<ystem.out.println!Z88888888888888888888888888888888888[$:
>hile!rs.previous!$$
6
<ystem.out.println!rs.#etInt!1$@[ [@rs.#et<trin#!2$@[ [@rs.#etBloat!3$@[ [@rs.#et<trin#!4$$:
;
;
;
2#: how to /enerate "croll"ensitive :esult "et and how to reflect the later updations fro*
database auto*aticall+ to the :esult"et object?
import (ava.s)l.8:
public class 3est
6
/ublic static void main!<trin#RS ar#s$thro+s -xception
6
.lass.for9ame!Zsun.(dbc.odbc.*dbc'dbcDriver[$:
.onnection con T Driver5ana#er.#et.onnection!Z(dbcodbcna#[,[system[,[dur#a[$:
<tatement st T
con.create<tatement!1esult<et.3C/-X<.1'HHX<-9<-I3IL-,1esult<et..'9.41X4/DA3A?H-$:
1esult<et rs T st.executeEuery!Zselect 8 from emp1[$:
rs.next!$:
<ystem.out.println!Zold salary emp111__.[@rs.#etBloat!3$$:
<ystem.in.read!$:77application is in pause, perform database updations
1s.refresh1o+!$:
<ystem.out.println!Zne+ salary of emp111__..[@rs.#etBloat!3$$:
;
;
>here refresh1o+!$ is a method from <crollable 1esult<et ob(ect, +hich can be used to
refresh the current ro+ in the 1esult<et ob(ect to allo+ the later updations from database. /rototype
of this method is
public void refresh1o+!$
2$: Cow to insert records into ,atabase throws &pdatable :esult"et?
If +e +ant to insert a ne+ record on to the database throu#h 4pdatable 1esult<et ob(ect, +e +ill use
the follo+in# steps.
"tep1 Oet the 4pdatable 1esult<et ob(ect +ith fetched data.
"tep2 5ove 1esult<et cursor to the end of the 1esult<et ob(ect, +here +e need to ta"e a buffer to
hold ne+ records data temporarily, for this +e use the follo+in# method from updatable 1esult<et
ob(ect.

public void move3oInsert1o+!$
"tep0 Insert ne+ records data on to the buffer temporarily at 4pdatable 1esult<et ob(ect for this
+e +ill use the follo+in# method format.
public void update^xx!int fieldno,xxx value$
>here xxx may be byte, short, int, char, double, float, lon#.
"tep3 5a"e the temporary insertion as the permanent insertion in 4pdatable 1esult<et ob(ect as +ill
as in database, for this +e+ill use the follo+in# method.
public void insert1o+!$
Ihe followin/ exa*ple de*onstrates how to insert no. of records onto the database
throu/h &pdatable :esult"et objects.

import (ava.s)l.8:
import (ava.io.8:
public class 4pdate1es-x
6
public static void main!<trin#RS ar#s$thro+s -xception
6
.lass.for9ame!Zsun.(dbc.odbc.*dbc'dbcDriver[$:
.onnection con T Driver5ana#er.#et.onnection!Z(dbcodbcna#[,[system[,[dur#a[$:
<tatement st T
con.create<tatement!1esult<et.3C/-X<.1'HHX<-9<-I3IL-,1esult<et..'9.41X4/DA3A?H-$:
1esult<et rs T st.executeEuery!Zselect 8 from emp1[$:
?uffered1eader br T ne+ ?uffered1eader!ne+ Input<tream1eader!<ystem.in$$:
rs.move3oInsert1o+!$:
+hile!true$
6
<ystem.out.println!Zenter employee number[$:
int eno T Inte#er.parseInt!br.readHine!$$:
<ystem.out.println!Zenter employee name[$:
<trin# ename T br.readHine!$:
<ystem.out.println!Zenter employee salary[$:
float esal T Bloat.parseBloat!br.readHine!$$:
<ystem.out.println!Zenter employee address[$:
<trin# eaddr T br.readHine!$:
rs.updateInt!1,eno$:
rs.update<trin#!2,ename$:
rs.updateBloat!3,esal$:
rs.update<trin#!4,eaddr$:
rs.insert1o+!$:
<ystem.out.println!Zrecord successfully inserted[$:
<ystem.out.println!Zone more recordRy7nS$:
<trin# option T br.readHine!$:
if!option.e)uals!Zn[$$
brea":
;
;
2%: Cow to perfor* updations on ,atabase throws &pdatable :esult"et?
?y usin# 4pdatable 1esul<et ob(ect +e are able to perform some updations on to the database. 3o
perform updations on to the database throu#h 4pdatable 1esult<et ob(ect +e +ill use the follo+in#
steps.
"tep1 Oet the 4pdatable 1esult<et ob(ectd +ith the fetched data.
"tep2 5ove 1esult<et cursor to a record +here +e +ant to perform updations, for this +e +ill use
the follo+in# method.
public void absolute!int recordno.$
"tep0 /erform 3emporary updations on to the particular record, for this +e +ill use follo+in#
method.
public void update^xx!int fieldno,xxx value$
"tep3 5a"e the temporary updation as a parmenent updation on to the 4pdatable 1esult<et ob(ect
as +ell as to the database. Bor this +e +ill use the follo+in# method.
public void update1o+!$
Ihe followin/ exa*ple de*onstrates how to perfor* updations on to the database throu/h
&pdatable :esult"et object.
import (ava.s)l.8:
public class 4pdate1es-x1
6
public static void main!<trin#RS ar#s$thro+s -xception
6
.lass.for9ame!Zsun.(dbc.odbc.*dbc'dbcDriver[$:
.onnection con T Driver5ana#er.#et.onnection!Z(dbcodbcna#[,[system[,[dur#a[$:
<tatement st T
con.create<tatement!1esult<et.3C/-X<.1'HHX<-9<-I3IL-,1esult<et..'9.41X4/DA3A?H-$:
1esult<et rs T st.executeEuery!Zselect 8 from emp1[$:
rs.absolute!3$:
float ne+sal T rs.#etBloat!3$@5JJ:
rs.updateBloat!3,ne+sal$:
rs.update1o+!$:
;
;
2':what is meant by 4esult)et;etaData ?How to 8et <he 4esult)et metadata o, a 4esult)et
ob&ect?
Data about the data is called as 5etadata. <imilarily data about the data available in 1esult<et
ob(ect called as Z1esult<et5etadata[.

1esult<et 5etadata includes the number of columns of a table in 1esult<et ob(ect, all the
column names, column datatypes and the column display siFes.
3o #et the 1esult<et 5etadata ob(ect +e +ill use the follo+in# method from 1esult<et ob(ect.
public 1esult<et5etaData #et5etaData!$
3o #et the number of columns available in 1esult<et ob(ect +e +ill use the follo+in# method
from 1esult<et5etaData ob(ect.
public int #et.olumn.ount!$
3o #et the name of a particular column, +e +ill use the follo+in# method.
public <trin# #et.olumn9ame!int fieldno$
3o #et the column datatype of a particular column, +e +ill use the follo+in# method
public <trin# #et.olumn3ype9ame!int fieldno$
3o #et the column display siFe of a particular column +e +ill use the follo+in# method.
public int #et.olumnDisplay<iFe!int fieldno$
Ihe followin/ exa*ple de*onstrates how to /et :esult"et)eta,ata fro* a :esult"et object
import (ava.s)l.8:
public class 1esult<et5D
6
public static void main!<trin#RS ar#s$thro+s -xception
6
.lass.for9ame!Zsun.(dbc.odbc.*dbc'dbcDriver[$:
.onnection con T Driver5ana#er.#et.onnection!Z(dbcodbcna#[,[system[,[dur#a[$:
<tatement st T con.create<tatement!$:
1esult<et rs T st.executeEuery!Zselect 8 from emp1[$:
1esult<et5etaData rsmd T rs.#et5etaData!$:
int count T rsmd.#et.olumn.ount!$:
<ystem.out.println!Znumber of columns......[@count$:
for!int iT1:i\Tcount:i@@$
6
<ystem.out.println!rsmd.#et.olumn9ame!i$@[ Z@rsmd.#et.olumn3ype9ame!i$@[
Z@rsmd.#et.olumnDisplay<iFe!i$$:
<ystem.out.println!$
;
;
;
2(: how to displa+ the data with the respective field na*es
import (ava.s)l.8:
public class 1<5D1
6
public static void main!<trin#RS ar#s$thro+s -xception
6
.lass.for9ame!Zsun.(dbc.odbc.*dbc'dbcDriver[$:
.onnection con T Driver5ana#er.#et.onnection!Z(dbcodbcna#[,[system[,[dur#a[$:
<tatement st T
con.create<tatement!1esult<et.3C/-X<.1'HHX<-9<-I3IL-,1esult<et..'9.41X4/DA3A?H-$:
1esult<et rs T st.executeEuery!Zselect 8 from emp1[$:
1esult<et5etaData rsmd T rs.#et5etaData!$:
<ystem.out.println!rsmd.#et.olumn9ame!1$@[ Z@rsmd.#et.olumn9ame!2$@[
Z@rsmd.#et.olumn9ame!3$@[ Z@rsmd.#et.olumn9ame!4$$:
<ystem.out.println!Z88888888888888888888888888888888[$:
+hile!rs.next!$$
6
<ystem.out.println!rs.#etInt!1$@[ Z@rs.#et<trin#!2$@[ Zrs.#etBloat!3$@[ Z@rs.#et<trin#!4$$:
;
;
;
29: What are the differences between "tate*ent and (repared"tate*ent?
.or0
Iell *e the situations where we should /o for (repared"tate*ent over "tate*ent object.
Ans:
>hen +e have a re)uirement to execute same "ind of s)l )uery in the next se)uence then +e
should #o for /repared<tatement over <tatement ob(ect.
Bor the above re)uirement if +e use <tatement ob(ect, every time execution of the same s)l
)uery D?- must perform )uery to"eniFation, )uery parsin#, )uery optimiFation and )uery
execution.
3his approach +ill increase burden to the D?-. 3o reduce burden to the D?- +e should #o for
an alternative. 3hat is /repared<tatement over <tatement ob(ect.
Bor the same re)uirement if +e use /repared<tatement ob(ect then for our complete
re)uirement D?- +ill #o for only one time )uery parsin# !to"eniFation, parsin#, optimiFation
and execution$:
If +e +ant to use /repared<tatement ob(ect for the above re)uirement then
+e +ill use follo+in# steps.
"tep1 /repare /repare<tatement ob(ect by providin# #eneraliFed s)l )uery format +ith the re)uired
number of parameters, for this +e +ill use the follo+in# method from <tatement ob(ect.
public /repared<tatement prepare<tatement!<trin# s)l)ueryformat$
!/ /repared<tatement pst T con.prepare<tatement!Zinsert into emp1 values!G,G,G,G$[$:
>hen *L5 encounters above instruction (vm +ill pic"up specified #eneraliFed s)l )uery format
and send to the D?-, here D?- +ill process )uery format only one time and prepare a ?uffer +ith the
specified parameters, called as Z)uery plan[. As a result /repared<tatement ob(ect +ill be created +ith
the parameters at (ava side.
"tep2 <et the values to parameters in /repared<tatement ob(ect. After #ettin# /repared<tatement
ob(ect +ith parameters, +e need to set some values to perform an operation, for this +e +ill use the
follo+in# method.
public void set^xx!int parano,xxx value$
+here xxx may be byte, short, char, int, lon#, float, double.
!/ pst.setInt!1,111$:
pst.set<trin#!2,[abc[$:
>hen *L5 encounters the above method then (vm +ill set the specified values to the
specified parameters at the /repared<tatement ob(ect, intern that parameter values could be reflected
to )uery plan.
"tep0 Oiven an intimation to D?- to perform the respective operation. After settin# the values to the
parameters +e should #ive an intimation to the D?- explicitly pic"up the values from )uery plan and
perform the operation specified in #eneraliFed s)l )uery format, for this +e +ill use the follo+in#
methods.
If the #eneraliFed s)l )uery belon#s to selection #roup then +e +ill use follo+in# method from
/repared<tatement ob(ect
public 1esult<et executeEuery!_$
If the #eneraliFed s)l )uery belon#s to updation #roup then +e +ill use the follo+in# method.
public int execute4pdate!_$
3-: Chow to insert nu*ber of records into a table throu/h (repared "tate*ent object.
import (ava.s)l.8:
import (ava.io.8:
public class /reparedInsert-x
6
public static void main!<trin#RS ar#s$thro+s -xception
6
.lass.for9ame!Zsun.(dbc.odbc.*dbc'dbcDriver[$:
.onnection con T Driver5ana#er.#et.onnection!Z(dbcodbcna#[,[system[,[dur#a[$:
/repared<tatement pstT con.prepare<tatement!Zinsert into emp1 values!G,G,G,G$[$:
?uffered1eader brT ne+ ?uffered1eader!ne+ Input<tream1eader!<ystem.in$$:
+hile!true$
6
: ;
;

31: how to update the database throu/h (repared"tate*ent object.
import (ava.s)l.8:
public class /repared4pdate-x
6
public static void main!<trin#RS ar#s$thro+s -xception
6
.lass.for9ame!Zsun.(dbc.odbc.*dbc'dbcDriver[$:
.onnection con T Driver5ana#er.#et.onnection!Z(dbcodbcna#[,[system[,[dur#a[$:
/repared<tatement pst T con.prepare<tatement!Zupdate emp1 set esal T esal@G >here esal\G[$:
/st.setInt!1,5JJ$:
/st.setBloat!2,1JJJJ.Jf$:
Int count T pst.execute4pdate!$:
<ystem.out.println!Zno. of records updated[@count$:
;
;
32:how to fetch the data fro* database throu/h (repared"tate*ent object.
import (ava.s)l.8:
public class 4pdate1es-x
6
public static void main!<trin#RS ar#s$thro+s -xception
6
.lass.for9ame!Zsun.(dbc.odbc.*dbc'dbcDriver[$:
.onnection con T Driver5ana#er.#et.onnection!Z(dbcodbcna#[,[system[,[dur#a[$:
/repared<tatement pst T con.prepare<tatement!Zselect 8 from emp1 +here esal\TG[$:
/st.setBloat!1,1JJJJ.Jf$:
1esult<et rs T pst.executeEuery!$:
<ystem.out.println!Z-9' -9A5- -<AH -ADD1[$:
<ystem.out.println!Z888888888888888888888888888888[$:
>hile!rs.next!$$
6
<ystem.out.println!rs.#etInt!1$@[ Z@rs.#et<trin#!2$@[ Z@rs.#etBloat!3$@[ Z@rs.#et<trin#!4$$:
;
;
;
33:What is meant by <ransaction? How it is "ossible to maintain <ransactions in
JD! a""lications?
3ransaction is nothin# but an unit of +or" performed by the applications.
-very transaction should have the follo+in# properties.
Atomicity
.onsistency
Isolation
Durability
>here atomicity is nothin# but perform all the operations or not to perform all the operations
in a transaction. 3hat is everytransaction must be in either success state or failure state.
As part of the (dbc applications +hen +e establish a connection automatically
the connection should have a default nature called as Zauto commit[.
Auto commit in the sense +hen +e send an s)l )uery to the connection then connection +ill
carry that to the D?- and ma"e the D?- to execute provided s)l )uery and store the results
on the database permanently.
3he connections default auto commit nature violates the transactions atomicity property.
3o preserve transactions atomicity property +e should chan#e the connections auto commit
nature to non0auto commit nature, for this +e +ill use the follo+in# method.

/ublic void setAuto.ommit!?oolean b$
>here bTtrue connection is in auto commit
And bTfalse connection not in auto commit.
If +e use connections non auto commit nature in our (dbc applications then +e must use
either commit or rollbac" operations explicitily as part of the transactions.
/ublic void commit!$
/ublic void rollbac"!$
Ihe followin/ exa*ple de*onstrates how to *aintain the transactions with ato*icit+
propert+ in the jdbcapplications.
import (ava.s)l.8:
public class 3ransaction-x
6
public static void main!<trin#RS ar#s$thro+s -xception
6
.onnection con T null:
try
6
.lass.for9ame!Zsun.(dbc.odbd.*dbc'dbcDriver[$:
.on T Driver5ana#er.#et.onnection!Z(dbcodbcna#[,[system[,[dur#a[$:
con.setAuto.ommit!Zfalse[$:
<tatement st T con.create<tatement!$:
st.execute4pdate!Zinsert into emp1 values!NNN,AfffA,NJJJ,AhhhA$[$:
st.execute4pdate!Zupdate emp1 set esal T esal05JJ +here esalMT babcA Z$:
st.execute4pdate!Zdelete emp1 +here esal\&JJJ[$:
con.commit!$:
;
catch!-xception e$
6
con.rollbac"!$:
<ystem.out.println!e$:
;
;
;
3#:What is meant by )ave=oint?How to use )ave"oints in JD! a""lications?
<ave point is a concept introduced by (dbc 3.J +hich can be used to bloc" a set of instructions
execution in the transactions committin# operation.
3o set a save point +e +ill use the follo+in# method.
public <ave/oint set<ave/oint!$
3o bloc" a set of s)l )ueries execution prior to the save point +e +ill use the follo+in#
method.
public void rollbac"!savepoint s$
3o release a savepoint +e +ill use the follo+in# method
public void release<ave/oint!$:
<ave/oint concept could not be supported be type1 driver, it could be supported by type4
driver.
-ven type 4 driver is supportin# up to set<ave/oint!$ and rollbac"!$ , not release<avepoint!$:

!/
import (ava.s)l.8:
public class <ave/oint-x
6
public static void main!<trin#RS ar#s$thro+s -xception
6
.onnection con T null:
try
6
.lass.for9ame!Zoracle.(dbc.driver.'racleDriver[$:
con T Driver5ana#er.#et.onnection!Z(dbcoraclethinaloca(host1521xe[,[system[,[dur#a[$:
con.setAuto.ommit!Zfalse[$:
<tatement st T con.create<tatement!$:
st.execute4pdate!Zinsert into emp1 values!111,AfffA,NJJJ,AhhhA$[$:
savepoint spT con.<avepoint!$:
st.execute4pdate!Zinsert into emp1 values!222,A###A,&JJJ,AiiiA$ Z$:
con.rollbac"!sp$:
st.execute4pdate!Zinsert into emp1 values!333,AhhhA,KJJJ,A(((A$[$:
con.commit!$:
;
catch!-xception e$
6
con.rollbac"!$:
<ystem.out.println!e$:
;
;
;
*sp
1. What is 6"( ? ,escribe its concept.
*ava <erver /a#es !*</$ is a server side component for the #eneration of dynamic information as the
response. ?est suitable to implement vie+ components !presentation layer components$. It is part of
<49As *2-- platform.
2 . !xplain the benefits of 6"(?
3hese are some of the benefits due to the usa#e of *</ they are
/ortability, reusability and lo#ic components of the lan#ua#e can be used across various platforms.
5emory and exception mana#ement.
2as +ide ran#e of A/I +hich increases the output functionality.
Ho+ maintenance and easy deployment.
1obust performance on multiple re)uests.
0. Is 6"( technolo/+ extensible?
Ces, it is. *</ technolo#y is extensible throu#h the development of custom actions, or ta#s, +hich are
encapsulated in ta# libraries.
3 .Can we i*ple*ent an interface in a 6"(?
9o
7 What are the advanta/es of 6"( over "ervlet?
1. ?est suitable for vie+ components
2. +e can separate presentation and business lo#ic
3. 3he *</ author not re)uired to have stron# (ava "no+led#e
4. If +e are performin# any chan#es to the *</, then not re)uired to recompile and reload
explicitly
5. >e can reduce development time.
9. ,ifferences between "ervlets and 6"(?
"ervlets 6"(
1. -est suitable for processin/ lo/ic 1. -est suitable for presentation lo/ic
2. we cannot separate business and
presentation lo/ic
2. "eparation of presentation
and businesslo/ic is possible
0. "ervlet developer should have stron/
knowled/e in 6ava
0.6"( author is not reDuired to have stron/
knowled/e in 6ava
3. Gor source code chan/es $we have to
perfor* explicitl+ co*pilation
3. Gor source code chan/es $it is not
reDuired to perfor* explicit co*pilation
7. :elativel+ develop*ent ti*e is *ore 7. :elativel+ develop*ent ti*e is less
; . !xplain the differences between A"( and 6"(?
3he bi# difference bet+een both of these technolo#ies lies +ith the desi#n of the soft+are. *</
technolo#y is server and platform independent +hereas A</ relies primarily on 5icrosoft technolo#ies.
< . Can I stop 6"( execution while in the *idst of processin/ a reDuest?
Ces. /reemptive termination of re)uest processin# on an error condition is a #ood +ay to maximiFe
the throu#hput of a hi#h0volume *</ en#ine. 3he tric" !assumin# *ava is your scriptin# lan#ua#e$ is to
use the return statement +hen +e +ant to terminate further processin#.
>. Cow to (rotect 6"(s fro* direct access ?
If the *</ is secured resource then +e can place inside >-?0I9B folder so that end user is not allo+ed
to access directly by the name. >e can provide the url pattern by confi#urin# in +eb.xml
SwebJappH
SservletH
SservletJna*eH,e*o 6"(SBservletJna*eH
SjspJfileHBW!-JI'GBtest.jspSBjspJfileH
SsevletH
SservletJ*appin/H
SservletJna*eH,e*o 6"(SBservletJna*eH
SurlJpatternHBtestSBurlJpatternH
SBservletJ*appin/H

..
SBwebJappH
1@. !xplain 6"( A(I ?
3he *</ A/I contains only one pac"a#e (avax.servlet.(sp
It contains the follo+in# 2 interfaces
1. 6sp(a/e
3his interface defines the t+o life cycle methods (spInit!$ and (spDestroy!$.
1. Cttp6sp(a/e
3his interface defines only one life cyle method X(sp<ervice!$ method.
-very #enerated servlet for the (sps should implement either *sp/a#e or 2ttp*sp/a#e interface
either directly or indirectly.
11. What are the lifec+cle phases of a 6"(?
Hife cycle of *</ contains the follo+in# phases
1. (a/e translation 0convertin# from .(sp file to .(ava file
2. (a/e co*pilation convertin# .(ava to .class file
3. (a/e loadin/ 3his class file is loaded.
4. Create an instance 0 Instance of servlet is created
5. jspInit12 method is called
6. Tjsp"ervice12 is called to handle service calls
&. jsp,estro+12 is called to destroy it +hen the servlet is not re)uired.

12. !xplain the lifeJc+cle *ehtods in 6"(?
3he jspInit120 3he container calls the (spInit!$ to initialiFe te servlet instance.It is called before any
other method, and is called only once for a servlet instance.
3he Tjspservice120 3he container calls the X(spservice!$ for each re)uest, passin# it the re)uest and
the response ob(ects.
3he jsp,estro+120 3he container calls this +hen it decides ta"e the instance out of service. It is the
last method called n the servlet instance.
10. ,ifference between Tjsp"ervice12 and other life c+cle *ethods.
*</ contains three life cycle methods namely (spInit! $, X(sp<ervice!$ and (spDestroy!$. In these,
(spInit!$ and (spDestroy!$ can be overridden and +e cannot override X(sp<ervice!$.
>ebcontainer al+ays #enerate X(sp<ervice!$ method +ith *</ content. If +e are +ritin# X(sp<ervice!$
method , then #enerated servlet contains 2 X(sp<ervice!$ methods +hich +ill cause compile time
error.
3o sho+ this difference X(sp<ervice!$ method is prefixed +ith bXA by the *</ container and the other
t+o methods (spInit!$ and (spDestroy!$ has no special prefixes.
13 What is the jspInit12 *ethod?
3he (spInit!$ method of the (avax.servlet.(sp.*sp/a#e interface is similar to the init!$ method of
servlets. 3his method is invo"ed by the container only once +hen a *</ pa#e is initialiFed. It can be
overridden by a pa#e author to initialiFe resources such as database and net+or" connections, and to
allo+ a *</ pa#e to read persistent confi#uration data.
15. What is the Tjsp"ervice12 *ethod?
<3he X(sp<ervice!$ method of the (avax.servlet.(sp.2ttp*sp/a#e interface is invo"ed every time a ne+
re)uest comes to a *</ pa#e. 3his method ta"es the 2ttp<ervlet1e)uest and 2ttp<ervlet1esponse
ob(ects as its ar#uments. A pa#e author cannot override this method, as its implementation is
provided by the container.
16. What is the jsp,estro+12 *ethod?
3he (spDestroy!$ method of the (avax.servlet.(sp.*sp/a#e interface is invo"ed by the container +hen a
*</ pa#e is about to be destroyed. 3his method is similar to the destroy!$ method of servlets. It can
be overridden by a pa#e author to perform any cleanup operation such as closin# a database
connection.
1&. What 6"( lifec+cle *ethods can I override?
>e can override (spInit!$ and (spDestroy!$ methods but +e cannot override X(sp<ervice!$ method.
1N. Cow can I override the jspInit12 and jsp,estro+12 *ethods within a 6"( pa/e?
?y usin# *</ declation ta#
\Y]
public void (spInit!$ 6
. . .
;
YM
\Y]
public void (spDestroy!$ 6
. . .
;
YM
1> . !xplain about translation and execution of 6ava "erver pa/es ?
A (ava server pa#e is executed +ithin a *ava container. A *ava container converts a *ava file into a
servlet. .onversion happens only once +hen the application is deployed onto the +eb server . Durin#
the process of compilation *ava compiler chec"s for modifications if any modifications are present it
+ould modify and then execute it.
2@ . Wh+ is Tjsp"ervice12 *ethod startin/ with an ETE while other life c+cle *ethods do not?
X(sp<ervice!$ method +ill be +ritten by the container hence any methods +hich are not to be
overridden by the end user are typically +ritten startin# +ith an %X%. 3his is the reason +hy +e don%t
override X(sp<ervice!$ method in any *</ pa#e.
21. Cow to preJco*pile 6"(?
Add jspTpreco*pile as a re)uest parameter and send a re)uest to the *</ file. 3his +ill ma"e the
(sp pre0compile.
httpBBlocalhost<@<@Bjsp1Btest.jsp?jspTpreco*pileKtrue
It causes excution of *</ life cycle until (spInit!$ method +ithout executin# X(sp<ervice!$ method.
22. Ihe benefits of preJco*pilin/ a 6"( pa/e?
It removes the start0up la# that occurs +hen a container must translate a *</ pa#e upon receipt of
the first re)uest.
23.Cow *an+ 6"( scriptin/ ele*ents and explain the*?
Inside *</ four types of scriptin# elements are allo+ed.
1. "criptlet SA an+ java code AH
.an be used to place (ava code.
2. declarative SAU 6ava declaration AH
.an be used to declare class level variables and methods
0. expression SAK java expression AH
3o print (ava expressions in the *</
3. co**ent SAJJ jsp co**ent JJAH
23. What is a "criptlet?
*</ scriptlet can be used to place (ava code.
<yntax
SA
An+ java code
AH
Ihe java code present in the scriptlet will be placed directl+ inside Tjsp"ervice12 *ethod .
27. What is a 6"( declarativeG
*</ declarations are used to declare class variables and methods !both instance and static$ in a *</
pa#e. 3hese declations +ill be placed directly at class level in the #enerated servlet and these are
available to the entire *</.
<yntax
SAU Ihis is *+ declarative AH
!/ SAU int j K 1@R AH
29. Cow can I declare *ethods within *+ 6"( pa/e?
>e can declare methods by usin# *</ declarative ta#.

SAU
public int add!inti,int($6
return i@(:
;
AH
2;. What is the difference bBw variable declared inside a declaration and variable declared
in scriplet ?

Lariable declared inside declaration part is treated as a instance variable and +ill be placed directly at
class level in the #enerated servlet.
SAU int k K 1@R AH
Lariable declared in a scriptlet +ill be placed inside X(sp<ervice!$ method of #enerated servlet.It acts
as local variable.
SA
int k K 1@R
AH
What is a !xpression?
*</ -xpression can be used to print expression to the *</.
<yntax

SAK java expression AH

-# \YT ne+ (ava.util.Date!$ YM
3he expression in expression ta# should not ends +ith semi0colon

3he expression value +ill become ar#ument to the out.pritln!$ method in the #enerated servlet
2N.What are the three kinds of co**ents in 6"( and whatEs the difference between the*?
3hree types of comments are allo+ed in *</
1. 6"( Co**ent
SAJJ this is jsp co**ent JJAH
3his is also "no+n as hidden comment and it is visible only in the *</ and in rest of phases of *</ life
cycle it is not visible.
1. CI)# Co**ent
SUJJ this is CI)l co**ent JJ H
3his is also "no+n as template text comment or output comment. It is visible in all phases of *</
includin# source code of #enerated response.
1. 6ava Co**ents.
With in the script lets we can use even java co**ents .
SA
BB sin/le line java co**ent
BV this is *ultiline co**ent VB
AH
3his type of comments also "no+n as scriptin# comments and these are visible in the #enerated
servlet also.
2>. What is output co**ent?
3he comment +hich is visible in the source of the response is called output comment.
SUJJ this is CI)l co**ent JJ H
0@. What is a Cidden Co**ent?

SAJJ this is jsp co**ent JJAH
3his is also "no+n as *</ comment and it is visible only in the *</ and in rest of phases of *</ life
cycle it is not visible.
01. Cow is scriptin/ disabled?
<criptin# is disabled by settin# the scriptin#0invalid element of the deployment descriptor to true. It is
a subelement of (sp0property0#roup. Its valid values are true and false. 3he syntax for disablin#
scriptin# is as follo+s
\(sp0property0#roupM
\url0patternM8.(sp\7url0patternM
\scriptin#0invalidMtrue\7scriptin#0invalidM
\7(sp0property0#roupM
02. What are the 6"( i*plicit objects?
Implicit ob(ects are by default available to the *</. ?ein# *</ author +e can use these and not
re)uired to create it explicitly.
1. re)uest
2. response
3. pa#e.ontext
4. session
5. application
6. out
&. confi#
N. pa#e
K. exception
00. Cow does 6"( handle runJti*e exceptions?
Cou can use the error(a/e attribute of the pa#e directive to have uncau#ht run0time
exceptions automatically for+arded to an error processin# pa#e.
Bor example
\Ya pa#e error/a#eT=error.(sp= YM redirects the bro+ser to the *</ pa#e error.(sp if an uncau#ht
exception is encountered durin# re)uest processin#.
>ithin error.(sp, if you indicate that it is an error0processin# pa#e, via the directive
\Ya pa#e is-rror/a#eT=true= YM
In the error pa#es +e can access exception implicit ob(ect.

03. Cow can I i*ple*ent a threadJsafe 6"( pa/e? What are the advanta/es and
,isadvanta/es of usin/ it?
Cou can ma"e your *</s thread0safe by havin# them implement the <in#le3hread5odel
interface. 3his is done by addin# the directive in the *</.
\Ya pa#e is3hread<afeT=false= YM
3he #enerated servlet can handle only one client re)uest at time so that +e can ma"e *</ as thread
safe. >e can overcome data inconsistency problems by this approach.
3he main limitation is it may affect the performance of the system.
07. What is the difference between "ervletContext and (a/eContext?
<ervlet.ontext Oives the information about the container and it represents an application.
/a#e.ontext Oives the information about the 1e)uest and it can provide all other implicit *</
ob(ects .
09 . Is there a wa+ to reference the LthisL variable within a 6"( pa/e?
Ces, there is. 3he pa#e implicit ob(ect is e)uivalent to =this=, and returns a reference to the #enerated
servlet.
0; . Can +ou *ake use of a "ervlet%utput"trea* object fro* within a 6"( pa/e?
Ces . ?y usin# #et'utput<tream!$ method on response implicit ob(ect +e can #et it.
0< .What is the pa/e directive is used to prevent a 6"( pa/e fro* auto*aticall+ creatin/ a
session?
session ob(ect is by default available to the *</. >e can ma"e it unavailable by usin# pa#e directive as
follo+s.
\Ya pa#e sessionT=false=M
0>. WhatEs a better approach for enablin/ threadJsafe servlets and 6"(s?
"in/leIhread)odel Interface or"+nchroni=ation?
<ynchroniFed "ey+ord is recommended to use to #et thread0safety.
3@. What are various attributes %f (a/e ,irective ?
/a#e directive contains the follo+in# 13 attributes.
1. lan#ua#e
2. extends
3. import
4. session
5. is3hread<afe
6. info
&. error/a#e
N. is-rror pa#e
K. content3ype
1J. is-HI#nored
11. buffer
12. autoBlush
13. pa#e-ncodin#
31 . !xplain about autoflush?
3his command is used to autoflush the contents. If a value of true is used it indicates to flush the
buffer +henever it is full. In case of false it indicates that an exception should be thro+n +henever the
buffer is full. If you are tryin# to access the pa#e at the time of conversion of a *</ into servlet
+ill result in error.
32. Cow do +ou restrict pa/e errors displa+ in the 6"( pa/e?
Cou first set =error/a#e= attribute of /AO- directive to the name of the error pa#e !ie
error/a#eT=error.(sp=$in your (sp pa#e .
3hen in the error.(sp pa#e set =is-rrorpa#eT314-=.
>hen an error occur in your (sp pa#e, then the control +ill be automatically for+ard to error pa#e.
30. What are the different scopes available fos 6"(s ?
3here are four types of scopes are allo+ed in the *</.
1. pa/e 0 +ith in the same pa#e
2. reDuest 0 after for+ard or include also you +ill #et the re)uest scope data.
3. session 0 after sen1edirect also you +ill #et the session scope data. All data stored in session
is available to end user till session closed or bro+ser closed.
4. application 0 Data +ill be available throu#hout the application. 'ne user can store data in
application scope and other can #et the data from application scope.
33. when do use application scope?
If +e +ant to ma"e our data available to the entire application then +e have to use application scope.
37. What are the different scope valiues for the Sjspuse-eanH?

3he different scope values for \(spuse?eanM are
1. pa#e
2. re)uest
3.session
4.application
39. Cow do I use a scriptlet to initiali=e a newl+ instantiated bean?
(spuse?ean action may optionally have a body. If the body is specified, its contents +ill be
automatically invo"ed +hen the specified bean is instantiated. 3ypically, the body +ill contain
scriptlets or (spset/roperty ta#s to initialiFe the ne+ly instantiated bean, althou#h you are not
restricted to usin# those alone.
3he follo+in# example sho+s the Ztoday[ property of the Boo bean initialiFed to the current date +hen
it is instantiated. 9ote that here, +e ma"e use of a *</ expression +ithin the (spset/roperty action.
\(spuse?ean idT=foo= classT=com.?ar.Boo= M
\(spset/roperty nameT=foo= propertyT=x=
valueT=\YT(ava.text.DateBormat.#etDateInstance!$.format!ne+ (ava.util.Date!$$ YM= 7 M
\Y00 scriptlets callin# bean setter methods #o here 00YM
\7(spuse?ean M
3; . Can a 6"( pa/e instantiate a seriali=ed bean?
9o problem] 3he use ?ean action specifies the bean9ame attribute, +hich can be used for indicatin# a
serialiFed bean.
Bor example
A couple of important points to note. Althou#h you +ould have to name your serialiFed file
=filename.ser=, you only indicate =filename= as the value for the bean9ame attribute. Also, you +ill
have to place your serialiFed file +ithin the >-?0I9B7(spbeans directory for it to be located by the *</
en#ine.
4N.Cow do we include static files within a jsp pa/e ?
>e can include static files in *</ by usin# include directive !static include$
\Ya include fileT[header.(sp[ YM
3he content of the header.(sp +ill be included in the current (sp at translation time. 2ence this
inclusion is also "no+n as static include.
4K.In 6"(s how *an+ wa+s are possible to perfor* inclusion?
In *</, +e can perform inclusion in the follo+in# +ays.

1. -+ include directive
\Ya include fileT[header.(sp[ YM
3he content of the header.(sp +ill be included in the current (sp at translation time. 2ence this
inclusion is also "no+n as static include.
1. -+ include action
\(spinclude pa#eT[header.(sp[ 7M
3he response of the (sp +ill be included in the current pa#e response at re)uest processin# time!run
time$ hence it is also "no+n as dynamic include.
1. b+ usin/ pa/eContext i*plicit object
\Y

pa#e.ontext.include!Z7header.(sp[$:
YM
3his inclusion also happened at re)uest processin# time!run time$.
1. b+ usin/ :eDuest,ispatcher object
\Y
1e)uestDispatcher rd T re)uest.#et1e)uestDispatcher!Z7header.(sp[$:
1d.incliude!re)uest,response$:
YM
5J.In which situation we can use static include and d+na*ic include in 6"(s ?
If the tar#et resource ! included resource$ +onAt chan#e fre)uently, then it is recommended to use
static include.
\Ya include fileT[header.(sp[ YM
If the tar#et resource!Included pa#e$ +ill chan#e fre)uently , then it is recommended to use dynamic
include.
\ (spinclude pa#eT[header.(sp[ 7M
-(b
12. What are the ,ifferences between !6- 0.@ and !6- 2.1?
Differences are
1$ -*? 3.J allo+s developers to pro#ram -*? components as ordinary *ava ob(ects +ith ordinary
*ava business interfaces rather than as heavy +ei#ht components li"e -*? 2 !home, remote$.
2$ In -*? 3.J you can use annotation or deployment descriptors but in -*? 2 you have to use
deployment descriptors.
3$ -*? 3 introduced persistence A/I for database access. In -*? 2 you can use -ntity bean.
4$ -*? 3.J is much faster the -*?2
22. What are the ke+ features of the !6- technolo/+?
1. -*? components are server0side components +ritten entirely in the *ava pro#rammin#
lan#ua#e
2. -*? components contain business lo#ic only 0 no system0level pro#rammin# Q services,
such as transactions, security, life0cycle, threadin#, persistence, etc. are automatically
mana#ed for the -*? component by the -*? server.
3. -*? architecture is inherently transactional, distributed, portable multi0tier, scalable and
secure.
4. -*? components are fully portable across any -*? server and any '<.
5. -*? architecture is +ire0protocol neutralVany protocol can be utiliFed li"e II'/,*15/, 233/,
D.'5,etc.
02. What is the difference between !6- and :)I
?oth of them are (ava solution for distributed computin#.
15I offers remote access to an ob(ect runnin# in another *L5 and no other services.
?ut -*? offers far more services than 15I apart from remote method callin#. -*? levera#es this
remote0ob(ect feature of 15I and '1? !15I0II'/$ +hich can be called by any .'?1A client, but also
provides other services such as persistence, transaction mana#ement, security, resource
mana#ement, ob(ect poolin# and messa#in#.
32.What are the wa+s for a client application to /et an !6- object?
1. 3he client has the *9DI name of the -*? ob(ect: this name is used to #et the -*? ob(ect.
2$ 3he client has the *9DI name of the 2ome ob(ect, this is a more usual case: this name is
used to #et the 2ome ob(ect, then a finder method is invo"ed on this 2ome to obtain one or
several entity bean ob(ects. 3he client may also invo"e a =create= method on the 2ome ob(ect
to create a ne+ -*? ob(ect !session or entity$.
3$ 3he client has #ot a handle on an -*? ob(ect. A handle is an ob(ect that identifies an -*?
ob(ect: it may be serialiFed, stored, and used later by a client to obtain a reference to the -*?
'b(ect, usin# the #et-*?'b(ect method!$.
4$ 3he client has #ot a reference to an -*? ob(ect, and some methods defined on the remote
interface of this -nterprise ?ean return -*? ob(ects.
72. What are the different kinds of enterprise beans?
<tateless session bean0 An instance of these non0persistent -*?s provides a service +ithout storin# an
interaction or conversation state bet+een methods. Any instance can be used for any client.
<tateful session bean0 An instance of these non0persistent -*?s maintains state across methods and
transactions. -ach instance is associated +ith a particular client.
-ntity bean0 An instance of these persistent -*?s represents an ob(ect vie+ of the data, usually ro+s
in a database. 3hey have a primary "ey as a uni)ue identifier. -ntity bean persistence can be either
container0mana#ed or bean0mana#ed.
5essa#e0driven bean0 An instance of these -*?s is inte#rated +ith the *ava 5essa#e <ervice !*5<$ to
provide the ability for messa#e0driven beans to act as a standard *5< messa#e consumer and perform
asynchronous processin# bet+een the server and the *5< messa#e producer.
92. What is !ntit+ -ean?
3he entity bean is used to represent data in the database. It provides an ob(ect0oriented interface to
data that +ould normally be accessed by the *D?. or some other bac"0end A/I. 5ore than that, entity
beans provide a component model that allo+s bean developers to focus their attention on
the business lo#ic of the bean, +hile the container ta"es care of mana#in# persistence,transactions,
and access control.
3here are t+o basic "inds of entity beans container0mana#ed ersistence !.5/$ andbean0mana#ed
persistence !?5/$.
.ontainer0mana#ed persistence beans are the simplest for the bean developer to create and the most
difficult for the -*? server to support. 3his is because all the lo#ic for synchroniFin# the bean%s state
+ith the database is handled automatically by the container. 3his means that the bean developer
doesn%t need to +rite any data access lo#ic, +hile the -*? server is
supposed to ta"e care of all the persistence needs automatically. >ith .5/, the container mana#es
the persistence of the entity bean. Lendor tools are used to map the entity fields to the database and
absolutely no database access code is +ritten in the beanclass.
3he bean0mana#ed persistence !?5/$ enterprise bean mana#es synchroniFin# its state +ith the
database as directed by the container. 3he bean uses a database A/I to read and +rite its fields to the
database, but the container tells it +hen to do each synchroniFation operation and mana#es the
transactions for the bean automatically. ?ean0mana#ed persistence #ives the beandeveloper the
flexibility to perform persistence operations that are too complicated for the container or to use a data
source that is not supported by the container.
;2. Wh+ does !6- needs two interfaces1Co*e and :e*ote Interface2?
3here is a pure division of roles bet+een the t+o .
2ome Interface is the +ay to communicate +ith the container +hich is responsible for creatin# ,
locatin# and removin# beans and 1emote Interface is the lin" to the bean that allo+s access to all
methods and members
<2.What is an !6- Context?
-*?.ontext is an interface that is implemented by the container, and it is also a part of the bean0
container contract. -ntity beans use a subclass of -*?.ontext called -ntity.ontext. <ession beans use
a subclass called <ession.ontext. 3hese -*?.ontext ob(ects provide the bean class +ith information
about its container, the client usin# the bean and the bean itself. 3hey also provide other functions.
<ee the A/I docs and the spec for more details
>2. ,oes the container create a separate instance of the /enerated !6-Co*e and !6-%bject
classes?
3he -*? container maintains an instance pool. 3he container uses these instances for the -*? 2ome
reference irrespective of the client re)uest. >hile referrin# the -*? 'b(ect classes the container
creates a separate instance for each client re)uest. 3he instance pool maintenance is up to the
implementation of the container. If the container provides one, it is available other+ise it is not
mandatory for the provider to implement it. 2avin# said that, yes most of the container providers
implement the poolin# functionality to increase the performance of the application server. 3he +ay it
is implemented is a#ain up to the implementer.
1@2. WhatEs difference between httpsession and !6- session bean ?
A session in a <ervlet, is maintained by the <ervlet .ontainer throu#h the 2ttp<ession ob(ect, that is
ac)uired throu#h the re)uest ob(ect. Cou cannot really instantiate a ne+ 2ttp<ession ob(ect, and it
doesn%t contains any business lo#ic, but is more of a place +here tostoreob(ects.
A session in -*? is maintained usin# the <ession?eans. Cou desi#n beans that can
contain business lo#ic, and that can be used by the clients. Cou have t+o different session beans
<tateful and <tateless. 3he first one is someho+ connected +ith a sin#le client. It maintains the state
for that client, can be used only by that client and +hen the client =dies= then the session bean is
=lost=.
A <tateless <ession ?ean doesn%t maintain any state and there is no #uarantee that the same client
+ill use the same stateless bean, even for t+o calls one after the other. 3he lifecycle of a <tateless
<ession -*? is sli#htly different from the one of a <tateful <ession -*?. Is -*? .ontainer%s
responsibility to ta"e care of "no+in# exactly ho+ to trac" each session and redirect the re)uest from
a client to the correct instance of a <ession ?ean. 3he +ay this is done is vendor dependant, and is
part of the contract.
112. What are the ke+ benefits of the !6- technolo/+?
1. 1apid application development
2. ?road industry adoption
3. Application portability
4. /rotection of I3 investment
122. Wh+ do we have a re*ove *ethod in both !6-Co*e and !6-%bject?
>ith the -*?2ome version of the remove, you are able to delete an entity bean +ithout first
instantiatin# it !you can provide a /rimary Iey ob(ect as a parameter to the remove method$. 3he
home version only +or"s for entity beans. 'n the other hand, the 1emote interface version +or"s on
an entity bean that you have already instantiated. In addition, the remote version also +or"s on
session beans !stateless and stateful$ to inform the container of your loss of interest in this bean.
102. What are the services provided b+ container?
.ontainer services are totally depends upon the =vendor implementation=. ?ut more or less most of
the vendors suppots the basic services li"e,
Hife.ycle 5ana#ement 0 It is Automatic...
1esource 5ana#ement 0.reatin# and destroyin# the ob(ects based the current load of re)uests for
better usa#e of memory.
<ession 5ana#ement 0 it is used by Developer coded callbac" methods...
3ransaction 5ana#ement 0 it is used by confi#urin# deployment
descriptor !DD$ ...
<ecurity mana#ement 0 it is used by confi#urin# deployment descriptor !DD$ ...
3he other services, if any +ill be in advanced versions, and depends on Lendor specific.
132. Is it possible to share an Cttp"ession between a 6"( and !6-? What happens when I
chan/e a value in the Cttp"ession fro* inside an !6-?
Cou can pass the 2ttp<ession as parameter to an -*? method, only if all ob(ects in session are
serialiFable. 3his has to be consider as Gpassed0by0valueG, that means that its read0only in the -*?. If
anythin# is altered from inside the -*?, it +onAt be reflected bac" to the 2ttp<ession of the <ervlet
.ontainer.3he Gpass0by0referenceG can be used bet+een -*?s 1emote Interfaces, as they are remote
references. >hile it I< possible to pass an 2ttp<ession as a parameter to an -*? ob(ect, it is
considered to be Gbad practice !1$G in terms of ob(ect oriented desi#n. 3his is because you are
creatin# an unnecessary couplin# bet+een bac"0end ob(ects !e(bs$ and front0end ob(ects
!2ttp<ession$. .reate a hi#her0level of abstraction for your e(bAs api. 1ather than passin# the +hole,
fat, 2ttp<ession !+hich carries +ith it a bunch of http semantics$, create a class that acts as a value
ob(ect !or structure$ that holds all the data you need to pass bac" and forth bet+een front0end7bac"0
end
172. What is the difference between a Coarse ?rained? !ntit+ -ean and a Gine ?rained?
!ntit+ -ean?
A Gfine #rainedG entity bean is pretty much directly mapped to one relational table, in third normal
form. A Gcoarse #rainedG entity bean is lar#er and more complex, either because its attributes include
values or lists from other tables, or because it Go+nsG one or more sets of dependent ob(ects. 9ote
that the coarse #rained bean mi#ht be mapped to a sin#le table or flat file, but that sin#le table is
#oin# to be pretty u#ly, +ith data copied from other tables, repeated field #roups, columns that are
dependent on non0"ey fields, etc. Bine #rained entities are #enerally considered a liability in lar#e
systems because they +ill tend to increase the load on several of the -*? serverGs subsystems !there
+ill be more ob(ects exported throu#h the distribution layer, more ob(ects participatin# in
transactions, more s"eletons in memory, more -*? 'b(ects in memory, etc.$
192. ,oes "tateful "ession bean support instance poolin/?
<tateful <ession ?ean conceptually doesn%t have instance poolin#.
>hat is the difference bet+een *ava?ean and -*?G
A *ava ?ean is a soft+are component +ritten in the *ava pro#rammin# lan#ua#e that conforms to the
*ava?eans component specification. 3he *ava?eans A/Is became part of the =core= *ava A/Is as of the
1.1 release of the *DI.
3he *ava?eans specification defines a *ava0based soft+are component model that adds a number of
features to the *ava pro#rammin# lan#ua#e. <ome of these features include
8 introspection
8 customiFation
8 events
8 properties
8 persistence
-nterprise *ava?eans !-*?s$ are *ava0based soft+are components that are built to comply +ith *ava%s
-*? specification and run inside of an -*? container supplied by a *2-- provider. An -*? container
provides distributed application functionality such astransaction support,
1;2. What are the Interfaces need to create to i*ple*ent "ession -ean with !x*aple?
<ession bean class !.art?ean$
2ome interface !.art2ome$
1emote interface !.art$
<ession bean class !.art?ean$
public class .art?ean implements <ession?ean 6
<trin# customer9ame:
<trin# customerId:
Lector contents:
public void e(b.reate!<trin# person$
thro+s .reate-xception 6
if !person TT null$ 6
thro+ ne+ .reate-xception!=9ull person not allo+ed.=$:
;
else 6
customer9ame T person:
;
customerId T =J=:
contents T ne+ Lector!$:
;
public void e(b.reate!<trin# person, <trin# id$
thro+s .reate-xception 6
if !person TT null$ 6
thro+ ne+ .reate-xception!=9ull person not allo+ed.=$:
;
else 6
customer9ame T person:
;
IdLerifier id.hec"er T ne+ IdLerifier!$:
if !id.hec"er.validate!id$$ 6
customerId T id:
;
else 6
thro+ ne+ .reate-xception!=Invalid id =@ id$:
;
contents T ne+ Lector!$:
;
public void add?oo"!<trin# title$ 6
contents.add-lement!title$:
;
public void remove?oo"!<trin# title$ thro+s ?oo"-xception 6
boolean result T contents.remove-lement!title$:
if !result TT false$ 6
thro+ ne+ ?oo"-xception!title @ =not in cart.=$:
;
;
public Lector #et.ontents!$ 6
return contents:
;
public .art?ean!$ 6;
public void e(b1emove!$ 6;
public void e(bActivate!$ 6;
public void e(b/assivate!$ 6;
public void set<ession.ontext!<ession.ontext sc$ 6;
;
2ome Interface
public interface .art2ome extends -*?2ome 6
.art create!<trin# person$ thro+s
1emote-xception, .reate-xception:
.art create!<trin# person, <trin# id$ thro+s
1emote-xception, .reate-xception:
;
3he si#natures of the e(b.reate and create methods are similar, but differ in important +ays. 3he
rules for definin# the si#natures of the create methods of a home interface follo+.
3he number and types of ar#uments in a create method must match those of its correspondin#
e(b.reate method.
3he ar#uments and return type of the create method must be valid 15I types.
A create method returns the remote interface type of the enterprise bean. !?ut an e(b.reate method
returns void.$
3he thro+s clause of the create method must include the (ava.rmi.1emote-xception and the
(avax.e(b..reate-xception
1emote Interface
public interface .art extends -*?'b(ect 6
public void add?oo"!<trin# title$ thro+s 1emote-xception:
public void remove?oo"!<trin# title$ thro+s
?oo"-xception, 1emote-xception:
public Lector #et.ontents!$ thro+s 1emote-xception:
;
3he method definitions in a remote interface must follo+ these rules
-ach method in the remote interface must match a method implemented in the enterprise bean class.
3he si#natures of the methods in the remote interface must be identical to the si#natures of the
correspondin# methods in the enterprise bean class.
3he ar#uments and return values must be valid 15I types.
3he thro+s clause must include the (ava.rmi.1emote-x
1<2. Cow *an+ !6- %bjects are created for a -ean?
Bor a <ession bean 0 one -*? ob(ect for one bean instance. Bor entity bean it depends, if 2 users are
accessin# one ro+ at time then one -*? ob(ect is used for both the beans other +ise for each bean
one -*? ob(ect.
1>2. What are the para*eters *ust follow for "ession -ean ?
It implements the <ession?ean interface.
3he class is defined as public.
3he class cannot be defined as abstract or final.
It implements one or more e(b.reate methods.
It implements the business methods.
It contains a public constructor +ith no parameters.
It must not define the finaliFe method.
2@2.When +ou will chose "tateful session bean and "tateless session bean?
<tateful session beans are used +hen there is converstional state and +hen there is a need of
temporary stora#e
<tateless session bean are used +hen there is no conversational state and +hen session bean has to
be used only for database access
212. What is the difference between "tateful session bean and "tateless session bean?
1. A stateful session beans can "eep data bet+een client accesses. +heras a stateless session
bean cannot.
2$ A stateful seesion bean contain the state of client after seesion is expired. +hereas a
stateless b+an cnanot.
3$ A stateful session beans use the bean of pools for client application n after use them it
return the bean in the pool. +hereas a stateless session bean cannot.
222. What are the callbacks *ethod in "ession -ean ?
public void e(b.reate!$ 6;
public void e(b1emove!$ 6;
public void e(bActivate!$ 6;
public void e(b/assivate!$ 6;
public void set<ession.ontext!<ession.ontext sc$ 6;
202. Cow is "tateful "ession bean *aintain their states with client?
>hen a client refers to a <tateful <ession ob(ect reference, all calls are directed to the same ob(ect on
the -*? container. 3he container does not re)uire client identity information or any coo"ie ob(ect to
use the correct ob(ect.
3his means that for a client to ensure that calls are directed to the same ob(ect on the container, all it
has to do is to use same reference for every call.
Bor example the follo+in# holds for all stateful session beans
<tateful2ome sfh T ...77#et home interface for stateful bean
<tateful bean1 T sfh.create!$:
<tateful bean2 T sfh.create!$:
if !bean1.isIdentical!bean1$$6; 77this is true]
if !bean1.isIdentical!bean2$$6; 77this is false]
779ote that the second test +ould evaluate to true for stateless beans
3hus, if you%re callin# a <tateful <ession ?ean from a servlet, your servlet need to "eep the reference
to the remote ob(ect in the 2ttp<ession ob(ect bet+een client calls for you to be able to direct calls to
the same ob(ect on the container.
Hi"e+ise, if you%re callin# from an application, you only obtain the reference to the bean once and
reuse the ob(ect throu#hout the application session.
232. What is the free pool?
3he free pool is a data structure the -*? container uses to cache anonymous instances of a #iven bean
type. 3he free poolimproves performance by reusin# ob(ects and s"ippin# container callbac"s +hen it
can.
272. Without ho*e and re*ote interfaces cant we i*ple*ent ejb?
>as (ust readin# about -*? 3.J. I suppose +ith -*? 3.J, 2ome interface is absolutely #one and
implementin# ?usiness Interface is not mandatory. All enterprise beans in -*? 3.J are (ust /'*' !/lain
'ld *ava 'b(ect$ +ith appropriate annotations.
292. When are stateless !6-s passivated?
<tateless e(bs are never passivated. <ince stateless e(bs do not have state, there is no need to
passivate them. 3hey are put bac" into the free pool after each method call so they +ill be available to
service other re)uests.
2;2. Is *ethod overloadin/ allowed in !6-?
Ces you can overload methods <hould synchroniFation primitives be used on bean methodsG 0 9o. 3he
-*? specification specificallystates that the enterprise bean is not allo+ed to use thread primitives. 3he
container is responsible for mana#in# concurrent access to beans at runtime.
2<2. What is handle and wh+ it is used in !6-?
3he handle mechanism allo+s a client application to maintain a reference to an -*? ob(ect. A handle
ob(ect may be obtained by callin# the #et2andle!$ method on the reference to an -*? ob(ect. 3he
main interest is that the handle class implements (ava.io.serialiFable interface, +hich means that a
handle may be serialiFed. 3his allo+s the client to store the handle, or to pass it to another process.
3he handle may then be deserialiFed and used to obtain the reference to the -*? ob(ect, by callin# the
#et-*?'b(ect!$ method.
2andles on session bean ob(ects are valid until the session bean ob(ect exists, i.e. their life time is
limited to that of the client. 2andles on entity bean ob(ects are valid durin# the complete life time of
the entity bean ob(ect: this means that such handles may be used by different clients and stored for a
lon# time: the -*? server holdin# the entity bean ob(ects may be stopped and restarted, the handle
+ill still be valid.
If +e consider the entity bean ob(ect of the example above !a2$, the +ay to obtain a handle on this
ob(ect is the follo+in# !the handle class is defined in the (avax.e(b pac"a#e$
2andle h T a2.#et2andle!$:3he handle ob(ect may then be serialiFed and stored in a file
'b(ect'utput<tream out T ne+ 'b(ect'utput<tream!ne+ Bile'utput<tream!=handlefile=$$:
out.+rite'b(ect!h$:
out.close!$:
3hen, a client can read the handle, and retrieve the referenced ob(ect
'b(ectInput<tream in T ne+ 'b(ectInput<tream!ne+ BileInput<tream!=handlefile=$$:
2andle h T !2andle$ in.read'b(ect!$:
Account a T !Account$/ortable1emote'b(ect.narro+!h.#et-*?'b(ect!$,
Account.class$:
3he -*? <pecification allo+s the client to obtain a handle for the home interface. 3his allo+s the client
to store a reference to an entity bean%s home interface in stable stora#e. 3he client code must use the
(avax.rmi./ortable1emote'b(ect.narro+!...$ method to convert the result of the #et-*?2ome!$
method invo"ed on a handle to the home interface type
2>2. I*ple*ent #ocal and :e*ote Interfaces in !6-?
1emote ?eans3he -*? 1.1 specification defines all -*?s as remote ob(ects. 3his means that every time
you ma"e a call to an -*?, you are ma"in# a remote call. 3his means that there is considerable
overhead to each -*? call, and hence performance implications. 3o combat this, server vendors
invented a +ay of circumventin# the remote calls to some de#ree. 'racle%s solution +ith '.4* +as the
pass0by0reference settin#, +hich determined +hether -*? ob(ects +ere communicated by reference to
the ob(ect, or +hether the +hole ob(ect had to be passed to the client.
An -*? has a remote interface and a home interface, +ith the exception of 5essa#eDriven?eans. 3he
remote interface extends the interface (avax.e(b.-*?'b(ect and the home interface extends the
interface (avax.e(b.-*?2ome. 3he -*? is accessible from any client, in any *L5, provided they have
the proper authoriFation.
Bor example, the 2ome and 1emote interfaces of an -*? called -5/ may loo" li"e this.
1emote
public interface -mp extends -*?'b(ect
6
lon# #et-mpno!$ thro+s 1emote-xception:
void set-mpno!lon# ne+Deptno$ thro+s 1emote-xception:
<trin# #et-name!$ thro+s 1emote-xception:
void set-name!<trin# ne+Dname$ thro+s 1emote-xception:
2ome
public interface Dept2ome extends -*?2ome
6
public -mp create!$ thro+s 1emote-xception, .reate-xception:
public Dept find?y/rimaryIey!Dept/I primaryIey$ thro+s 1emote-xception, Binder-xception:
9ote that both the home and the remote interface thro+ a 1emote-xception in all of their
method definitions. 3he e(b0(ar.xml deployment descriptor for these -*?s +ould loo" somethin# li"e
the snippets belo+
\entityM
\e(b0nameM-mp\7e(b0nameM
\homeMe(b.cmplocal.-mp2ome\7homeM
\remoteMe(b.cmplocal.-mp\7remoteM
\e(b0classMe(b.cmplocal.-mp?ean\7e(b0classM
.
.
.
Hocal ?eans3he -*? 2.J specification standardiFe a means of ma"in# local connections to -*?s
+ith Hocal Interfaces.
Bor an -*? to be classed as a local -*?, it must implement the local versions of the home and remote
interfaces, (avax.e(b.-*?Hocal'b(ect for the 2ome interface, and (avax.e(b.-*?Hocal2ome. Bor a client
to call the Hocal interface, they must be runnin# in the same *L5 as the *L5 that the -*? exists in.
3his means that not only an -*? can call a local -*? , <ervlets or *</s can also call the -*? via
it%s local interface if they are pac"a#ed to#ether as part of same application.
Bor example, the Hocal2ome and Hocal interfaces of an -*? called -5/ may loo" li"e this.
Hocal
public interface -mp extends -*?Hocal'b(ect
6
lon# #et-mpno!$:
void set-mpno!lon# ne+-mpno$:
<trin# #et-name!$:
void set-name!<trin# ne+-name$:
Hocal2ome
public interface -mp2ome extends -*?Hocal2ome
6
public -mp create!$ thro+s .reate-xception:
public -mp find?y/rimaryIey!-mp/I primaryIey$ thro+s Binder-xception:
3he e(b0(ar.xml deployment descriptor for these -*?s +ould loo" somethin# li"e the snippets belo+
\entityM
\e(b0nameM-mp\7e(b0nameM
\local0homeMe(b.cmplocal.-mp2ome\7local0homeM
\localMe(b.cmplocal.-mp\7localM
\e(b0classMe(b.cmplocal.-mp?ean\7e(b0classM
\cmp0versionM2.x\7cmp0versionM
\abstract0schema0nameM-mp\7abstract0schema0nameM
.
.
.
9ote that no+ the local interfaces no lon#er thro+ the 1emote-xception, sho+in# that they are not
remotely called methods. Also, the ^5H contains different elements. 3here is no+ a local0home and a
local ta#. Also +e are declarin# that this is an -*? 2.x bean, usin# the cmp0version ta#.
.allin# Hocal ?eans.allin# a local bean from *ava code is very simple, and very similar to usin# a
remote bean. 3he code to call a remote bean is sho+n belo+.
try
6
.ontext ctx T ne+ Initial.ontext!$:
'b(ect o T ctx.loo"up!=-mp=$:
-mp2ome emp2ome T /ortable1emote'b(ect.narro+!o, -mp2ome.class$
return emp2ome.find?yDeptno!#etDeptno!$$:
;
catch !1emote-xception r$
6
<ystem.err.println!=-rror loadin# -mployees!1emote$ = @ r.#et5essa#e!$$: return null:
;
catch !9amin#-xception n$
6
<ystem.err.println!=-rror loadin# -mployees!9amin#$ = @ n.#et5essa#e!$$:
return null:
;
catch !Binder-xception f$
6
<ystem.err.println!=-rror loadin# -mployees!Binder$ = @ f.#et5essa#e!$$:
return null:
;
3he code for a local bean is similar, but +e no lon#er have to +orry about the /ortable1emote'b(ect,
as the bean is no lon#er remote.
try
6
.ontext ctx T ne+ Initial.ontext!$:
'b(ect o T ctx.loo"up!=(avacomp7env7Hocal-mp=$:
-mp2ome emp2ome T !-mp2ome$o:
return emp2ome.find?yDeptno!#etDeptno!$$:
;
catch !9amin#-xception n$
6
<ystem.err.println!=-rror loadin# -mployees!9amin#$ = @ n.#et5essa#e!$$:
return null:
;
catch !Binder-xception f$
6
<ystem.err.println!=-rror loadin# -mployees!Binder$ = @ f.#et5essa#e!$$:
return null:
;
As you can see, the local bean has to loo"up the -*? sli#htly differently, even thou#h they are runnin#
in the same container. Also, there is no 1emote-xception thro+n by the find or the create methods, so
the exception does not have to be cau#ht.
3here is one more difference, and that is in the e(b0(ar.xml deployment descriptor. Bor an -*? to loo"
up a local -*?, it must point to the correct location usin# an \e(b0local0refM ta#. If this is not used,
the container +ill not be able to find the bean. Bor each -*? that needs to use the local -*?, the ^5H
belo+ must be in the deployment descriptor.
\entityM
\e(b0nameMDept\7e(b0nameM
.
.
.
\e(b0local0refM
\e(b0ref0nameMHocal-mp\7e(b0ref0nameM
\e(b0ref0typeM-ntity\7e(b0ref0typeM
\local0homeMe(b.cmplocal.-mp2ome\7local0homeM
\localMe(b.cmplocal.-mp\7localM
\e(b0lin"M-mp\7e(b0lin"M
\7e(b0local0refM
\7entityM
3his example +ill allo+ the -*? Dept to call the local -*? -mp usin# the name Hocal-mp. 3his is
re)uired because -*?s can have both local and remote interfaces, and to call the -*? -mp via it%s
remote interface the -*? Dept +ould loo" up the name -mp rather than the local reference
Hocal2ome.
0@2. Cow can I call one !6- fro* inside of another !6-?
In case of 1emote
-*?s can be clients of other -*?s. It (ust +or"s. 1eally. 4se *9DI to locate the 2ome Interface of the
other bean, then ac)uire an instance reference.
Bor -xample .ontext ctx T ne+ Initial.ontext!$:
77#et 2ome interface of bean
77narro+ 0retype
-mp2ome lhome T !-mp2ome $
(avax.rmi./ortable1emote'b(ect.narro+!ctx.loo"up!=(avacomp7env7Hocal-mp=$, -mp2ome .class$:
77#et remote interface
-mplbean T lhome.create!$:
77no+ you can call bussiness method on remote interface li"e
lbean.do<omethin#!$
Incase of Hocal but +e no lon#er have to +orry about the /ortable1emote'b(ect, as the bean is no
lon#er remote
.ontext ctx T ne+ Initial.ontext!$:
'b(ect o T ctx.loo"up!=(avacomp7env7Hocal-mp=$:
-mp2ome emp2ome T !-mp2ome$o:
012. What is the difference between )essa/e ,riven -eans and "tateless "ession
beans
In several +ays, the dynamic creation and allocation of messa#e0driven bean instances mimics the
behavior of stateless session -*? instances, +hich exist only for the duration of a particular method
call. 2o+ever, messa#e0driven beans are different from stateless session -*?s !and other types of
-*?s$ in several si#nificant +ays
5essa#e0driven beans process multiple *5< messa#es asynchronously, rather than processin# a
serialiFed se)uence of method calls.
5essa#e0driven beans have no home or remote interface, and therefore cannot be directly accessed
by internal or external clients. .lients interact +ith messa#e0driven beans only indirectly, by sendin# a
messa#e to a *5< Eueue or 3opic.
9ote 'nly the container directly interacts +ith a messa#e0driven bean by creatin# bean instances and
passin# *5< messa#es to those instances as necessary.
3he .ontainer maintains the entire lifecycle of a messa#e0driven bean: instances cannot be created or
removed as a result of client re)uests or other A/I calls
022. Can +ou control when passivation occurs?
3he developer, accordin# to the specification, cannot directly control +hen passivation occurs.
Althou#h for <tateful <ession ?eans,the container cannot passivate an instance that is inside a
transaction. <o usin# transactions can be a a strate#y to controlpassivation.
3he e(b/assivate!$ method is called durin# passivation, so the developer has control over +hat to do
durin# this exercise and can implement the re)uire optimiFed lo#ic.
<ome -*? containers, such as ?-A >ebHo#ic, provide the ability to tune the container to
minimiFe passivation calls.
3a"en from the >ebHo#ic 6.J D3D 0=3he passivation0strate#y can be either =default= or =transaction=.
>ith the default settin# the container +ill attempt to "eep a +or"in# set of beans in the cache. >ith
the =transaction= settin#, the container +ill passivate the bean after every transaction !or method call
for a non0transactional invocation$.
002. Cow to call an+ !6- fro* a servletB6"(B6ava Client?
.ontext ctx T ne+ Initial.ontext!$:
77#et 2ome interface of bean
77narro+ 0retype
?ean2ome lhome T !?ean2ome$ (avax.rmi./ortable1emote'b(ect.narro+!ctx.loo"up!=cF.train.?ean=$,
?ean2ome.class$:
77#et remote interface
?ean lbean T lhome.create!$:
77no+ you can call bussiness method on remote interface li"e
lbean.do<omethin#!$
032. Can the pri*ar+ ke+ in the entit+ bean be a 6ava pri*itive t+pe such as int?
3he primary "ey can%t be a primitive type00use the primitive +rapper classes, instead. Bor example,
you can use (ava.lan#.Inte#er as the primary "ey class, but not int !it has to be a class, not a
primitive$
072. What are the *ethods of !ntit+ -ean?
An entity bean consists of 4 #roups of methods
1. create methods 3o create a ne+ instance of a .5/ entity bean, and therefore insert data into the
database, the create!$ method on the bean%s home interface must be invo"ed. 3hey loo" li"e this
-ntity?ean.lass e(b.reate^^^!parameters$, +here -ntity?ean.lass is an -ntity ?ean you are tryin# to
instantiate, e(b.reate^^^!parameters$ methods are used for creatin# -ntity ?ean instances accordin#
to the parameters specified and to some pro#rammer0defined conditions.
A bean%s home interface may declare Fero or more create!$ methods, each of +hich must have
correspondin# e(b.reate!$ and e(b/ost.reate!$ methods in the bean class. 3hese creation methods are
lin"ed at run time, so that +hen a create!$ method is invo"ed on the home interface, the
container dele#ates the invocation to the correspondin# e(b.reate!$ and e(b/ost.reate!$ methods
on the bean class.
2. finder methods 3he methods in the home interface that be#in +ith =find= are called the find
methods. 3hese are used to )uery the -*? server for specific entity beans, based on the name of the
method and ar#uments passed. 4nfortunately, there is no standard )uery lan#ua#e defined for find
methods, so each vendor +ill implement the find method differently. In .5/ entity beans, the find
methods are not implemented +ith matchin# methods in the bean class: containers implement them
+hen the beanis deployed in a vendor specific manner. 3he deployer +ill use vendor specific tools to
tell the container ho+ a particular find method should behave. <ome vendors +ill use ob(ect0relational
mappin# tools to define the behavior of a find method +hile others +ill simply re)uire the deployer to
enter the appropriate <EH command.
3here are t+o basic "inds of find methods sin#le0entity and multi0entity. <in#le0entity find methods
return a remote reference to the one specific entity bean that matches the find re)uest. If no entity
beans are found, the method thro+s an 'b(ect9otBound-xception . -very entity bean must define the
sin#le0entity find method +ith the method name find?y/rimaryIey!$, +hich ta"es the bean%s primary
"ey type as an ar#ument.
3he multi0entity find methods return a collection ! -numeration or .ollection type$ of entities that
match the find re)uest. If no entities are found, the multi0entity find returns an empty collection.
3. remove methods 3hese methods !you may have up to 2 remove methods, or don%t have them at
all$ allo+ the client to physically remove -ntity beans by specifyin# either 2andle or a /rimary Iey for
the -ntity ?ean.
4. home methods 3hese methods are desi#ned and implemented by a developer, and -*?
specification doesn%t have any re)uirements for them except the need to thro+ a 1emote-xception is
each home method.
092. What is the difference between ContainerJ)ana/ed (ersistent 1C)(2 bean and -eanJ
)ana/ed (ersistent1-)(2 ?
.ontainer0mana#ed persistence!.5/$ beans are the simplest for the bean developer to create and the
most difficult for the -*? server to support. 3his is because all the lo#ic for synchroniFin# the bean%s
state +ith the database is handled automatically by the container. 3his means that the bean developer
doesn%t need to +rite any data access lo#ic, +hile the -*? server is supposed to ta"e care of all the
persistence needs automatically. >ith .5/, the container mana#es the persistence of the entity bean.
A .5/ bean developer doesn%t need to +orry about *D?. code and transactions, because the
.ontainer performs database calls and transaction mana#ement instead of the pro#rammer. Lendor
tools are used to map the entity fields to the database and absolutely no database access code is
+ritten in the bean class. All table mappin# is specified in the deployment descriptor. 'ther+ise, a
?5/ bean developer ta"es the load of lin"in# an application and a database on his shoulders.
3he bean0mana#ed persistence !?5/$ enterprise bean mana#es synchroniFin# its state +ith the
database as directed by the container. 3he bean uses a database A/I to read and +rite its fields to the
database, but the container tells it +hen to do each synchroniFation operation and mana#es the
transactions for the bean automatically. ?ean0mana#ed persistence #ives the beandeveloper the
flexibility to perform persistence operations that are too complicated for the container or to use a data
source that is not supported by the container.?5/ beans are not 1JJY database0independent,
because they may contain database0specific code, but .5/ beans are unable to perform complicated
D5H !data manipulation lan#ua#e$ statements. -*? 2.J specification introduced some ne+ +ays of
)ueryin# database !by usin# the -*? EH 0 )uery lan#ua#e$.
0;2.Can !ntit+ -eans have no create12 *ethods?
Ces. In some cases the data is inserted 9'3 usin# *ava application, so you may only need to retrieve
the information, perform its processin#, but not create your o+n information of this "ind
0<2. What is bean *ana/ed transaction?
If a developer doesn%t +ant a .ontainer to mana#e transactions, it%s possible to implement all
database operations manually by +ritin# the appropriate *D?. code. 3his often leads to productivity
increase, but it ma"es an -ntity ?ean incompatible +ith some databases and it enlar#es the amount of
code to be +ritten. All transaction mana#ement is explicitly performed by a developer.
0>2. What are transaction isolation levels in !6-?
1. 3ransactionXreadXuncommitted0 Allo+s a method to read uncommitted data from a D?!fast
but not +ise$.
2. 3ransactionXreadXcommitted0 Ouarantees that the data you are #ettin# has been
committed.
3. 3ransactionXrepeatableXread 0 Ouarantees that all reads of the database +ill be the same
durin# the transaction !#ood for read and update operations$.
4. 3ransactionXserialiFable0 All the transactions for resource are performed serial.
3@2. What is the difference between ejbCreate12 and ejb(ostCreate
3he purpose of e(b/ost.reate!$ is to perform clean0up database operations after <EH I9<-13s !+hich
occur +hen e(b.reate!$ is called$ +hen +or"in# +ith .5/ entity beans. e(b.reate!$ is called before
database I9<-13 operations. Cou need to use e(b/ost.reate!$ to define operations, li"e set a fla#,
after I9<-13 completes successfully.
>hen +or"in# +ith ?5/ entity beans, this is not necessary. Cou have full control over the entire
process, so you can place all the necessary lo#ic surroundin# your I9<-13 statement directly in the
e(b.reate!$ method.
-ven if you are creatin# ?5/ entity beans, the recommendation +ould still be to include an empty
e(b/ost.reate!$ method. Althou#h some application servers +ill not enforce it, the spec indicates that
this placeholder should be there.
312.What is the difference between sessioncontext and entit+context?
<ince -nterprise?eans live in a mana#ed container,the container is free to call your -*? components
methods at its leisure.
3he container houses the information li"e current status of bean,security credentials of the user
currently accessin# the bean in one ob(ect is called -*?.ontext 'b(ect.
A context represents a +ay for beans to perform callbac"s and modify their current status
<ession.ontext is -*? context for session bean
-ntity.ontext is -*? context for entity bean
5essa#e driven context is -*? context for messa#e driven bean
322. What is the difference between ejb"tore12 and ejb#oad12?
e(b<tore!$ +ill be called before e(b/assivate!$ and is used to store the ob(ect to persistent database.
e(bHoad!$ +ill be called before e(bActivate!$ and is used to retrieve the ob(ect from persistence
datastore.
302. What is the difference between !A:$ 6A: and WA: file?
62!! defines three t+pes of archives
1. *ava Archives !*A1$cA *A1 file encapsulates one or more *ava
classes, a manifest, and a descriptor. *A1 files are the lo+est
level of archive. *A1 files are used in *2-- for pac"a#in# -*?s
and client0side *ava Applications .
2. >eb Archives !>A1$c>A1 files are similar to *A1 files, except
that they are specifically for +eb applications made from
<ervlets, *</s, and supportin# classes.
3. -nterprise Archives !-A1$cAn -A1 file contains all of the
components that ma"e up a particular *2-- application.
332.Cow to i*ple*ent an entit+ bean which the (ri*ar+Fe+ is an autonu*eric?
3he -*? 2 <pec !1J.N.3 0 <pecial case 4n"no+n primary "ey class$ says that in cases +here the
/rimaryIeys are #enerated automatically by the underlyin# database, thebean provider
must declare the find?y/rimaryIey method to return (ava.lan#.'b(ect and specify the /rimary Iey
.lass as (ava.lan#.'b(ect in the Deployment Descriptor.
>hen definin# the /rimary Iey for the -nterprise ?ean, the Deployer usin# the .ontainer /rovider%s
tools +ill typically add additional container0mana#ed fields to the concrete subclass of theentity bean
class.
In this case, the .ontainer must #enerate the /rimary Iey value +hen the entity bean instance is
created !and before e(b/ost.reate is invo"ed on the instance.$
372. Is ,ecorator an !6- desi/n pattern?
9o. Decorator desi#n pattern, is the one +hich exhibits very lo+ level runtime polymorphism, for the
specific and sin#le ob(ect !Instance of the class$, but not for atleast for a class. It is the stuff to add
specific functionality to a sin#le Q pointed ob(ect and leaves others li"e it unmodified. It is havin# close
similarities li"e aspect stuff, but not +ith -*? stuff.
392. What is la=+ loadin/?
HaFy loadin# means not creatin# an ob(ect until the first time it is accessed. HaFy loadin# typically
loo"s li"e this
public class -xample 6
private Lector data T null:
public Lector #etData!$ 6
if !this.data TT null$ 6
this.data T ne+ Lector!$:
77 Hoad data into vector ...
;
return this.data:
;
;
3his techni)ue is most useful +hen you have lar#e hierarchies of ob(ects !such as a product catalo#$.
Cou can laFy0load subordinate ob(ects as you navi#ate do+n the hierarchy, and thereby only creat
ob(ects +hen you need them.
3;2. What is )essa/e ,riven -ean?
An 5D? is essentially a messa#e consumer that can listen to a messa#e destination or a messa#e
endpoint and #ets activated +hen a messa#e arrives. ?y desi#n, 5D?s are anonymous in nature and
hence cannot be directly invo"ed by a client. 3he only +ay to invo"e an 5D? is to send a messa#e to
the destination or endpoint to +hich it is listenin#. As 5D?s are stateless in nature and are not related
to any specific client, they can be pooled for concurrent processin# of messa#es.
3<2. What is C):?
.51 is an acronym for .ontainer 5ana#ed 1elation0ships.
.51, represented by the cmr fields in the deployment descriptor, +hich represents the relationship
exists bet+een different entities !entity beans$, +hich are in turn exhibitin# the database to the real
+orld. 3he relationships are one0one, one0many, Q many0many.
All the relations7 referential inte#rities +ill be mana#ed by container, then the definition%s in the
deployment descriptor%s are called as .ontainer 5ana#ed 1elationships !.51$..
3>2. Can a "ession -ean be defined without ejbCreate12 *ethod?
3he e(b.reate!$ methods is part of the bean%s lifecycle, so, the compiler +ill not return an error
because there is no e(b.reate!$ method.
2o+ever, the *2-- spec is explicit
the home interface of a <tateless <ession ?ean must have a sin#le create!$ method +ith no
ar#uments,
+hile the session bean class must contain exactly one e(b.reate!$ method, also +ithout ar#uments.
<tateful <ession ?eans can have ar#uments !more than one create method$
7@2. What are the optional clauses in !6- Q#?
>2-1- and '1D-1?C clauses are optional in -*? EH +here as <-H-.3 and B1'5 are re)uired
clauses.
712. Can I use session beans and hibernate 1instead of entit+ beans2 for persitance?
Ces, +e can. It%s same as ?5/.
722. If session has thrown Applicaiton!xception would +ou use !6-Context. set:oll-ack%nl+
*ethod?
Accordin# to the -*? specification, +hen the Application-xception is thro+n, the
-*?.ontext.set1oll?ac"'nly method is not called.
3ypically, an enterprise bean mar"s a transaction for rollbac" to protect data inte#rity before thro+in#
an application exception, because application exceptions do not automatically cause the .ontainer to
rollbac" thetransaction.
Bor example, an Account3ransfer bean +hich debits one account and credits another account could
mar" a transaction for rollbac" if it successfully performs the debit operation, but encounters a failure
durin# the credit operation.
702. What is the difference between activation and passivation?
3his +ould be the difference bet+een Activation and /assivation
>hile the bean is in the ready sta#e, the -*? container may decide to deactivate, or passivate, the
bean by movin# it from memory to secondary stora#e. !3ypically, the -*? container uses a least0
recently0used al#orithm to select a bean for passivation.$ 3he -*? container invo"es the bean%s
e(b/assivate method immediately before passivatin# it. If a client invo"es a business method on the
bean +hile it is in the passive sta#e, the -*? container activates the bean, movin# it bac" to the ready
sta#e, and then callsthe bean%s e(bActivate method.
732. Cow do +ou check whether the session is active in "tateful session bean ?
In <tateful session bean session is not itself a separate entity. it is contained in the bean it self. <o in
order to chec" tht +e need the chec" +hether the <tateful session bean is present or not +hich is
done by (ust invo"in# the home interface +ith the (ndi
772. What is the difference between find and select *ethods in !6-?
d A select method can return a persistent field !or a collection thereof$ of a related entity bean. A
finder method can return only a local or remote interface !or a collection of interfaces$.
d ?ecause it is not exposed in any of the local or remote interfaces, a select method cannot be
invo"ed by a client. It can be invo"ed only by the methods implemented +ithin the entity bean class.
A select method is usually invo"ed by either a business or a home method.
d A select method is defined in the entity bean class. Bor bean0mana#ed persistence, a finder method
is defined in the entity bean class, but for container0mana#ed persistence it is not.
792. What is the difference between local interface and re*ote interface?
>e can describe the follo+in# common rules for choosin# +hether to use remote client vie+ or local
client vie+
>hen you +ill potentially use a distributed environment !if your enterprise bean should be
independent of its deployment place$, you should obviously choose remote client vie+.
4se remote client vie+ +hen you need to be sure that parameters passed bet+een your -*? and the
client !and7or other enterprise beans$ should be passed =by value= instead of =by reference.= >ith
pass0by0value, the bean +ill have its o+n copy of the data, completely separated from the copy of the
data at the client. >ith local client vie+, you can do pass0by0reference, +hich means your bean, as
+ell as the client, +ill +or" directly +ith one copy of the data. Any chan#es made by the bean +ill be
seen by the client and vice versa. /ass0by0reference eliminates time7system expenses for copyin#
data variables, +hich provides a performance advanta#e.
If you create an entity bean, you need to remember that it is usually used +ith a local client vie+. If
your entity bean needs to provide access to a client outside of the existin# *L5 !i.e., a remote client$,
you typically use a session bean +ith a remote client vie+. 3his is the so0called <ession Bacade
pattern, the #oal of +hich is that the session bean provides the remote client access to the entity
bean.
If you +ant to use container0mana#ed relationship !.51$ in your enterprise bean, you must expose
local interfaces, and thus use local client vie+. 3his is mentioned in the -*? specification.
-nterprise beans that are ti#htly coupled lo#ically are #ood candidates for usin# local client vie+. In
other +ords, if one enterprise bean is al+ays associated +ith another, it is perfectly appropriate to co0
locate them !i.e., deploy them both in one *L5$ and or#aniFe them throu#h a local interface.
7;2. Wh+ C)( beans are abstract classes?
>e have to provide abstract data to ob(ect mappin# that maps the fields in our bean to a batabase,
and abstract methods methods that corelate these fields.
7<2. What is the difference between nor*al 6ava object and !6-?
*ava 'b(ect is a reusable component.
-*? is a distributed component used to develop business applications. .ontainer provides runtime
environment for -*?s.
7>2. What is abstract sche*a?
Abstract schema is part of an entity bean%s deployment descriptor +hich defines the bean%s persistent
fields and their relationship.Abstract schema is specifed for entity beans +ith container mana#ed
persistence. >e specify the name of the Abstract schema name in the deployment descriptor. 3he
)ueries +ritten in -*? EH for the finder methods references this name. 3he information provided in
this Abstract <chema is used by the container for persistence mana#ement and relationship
mana#ement.
9@2. What is clusterin/. What are the different al/orith*s used for clusterin/?
.lusterin# is the use of multiple computers and stora#e devices to create +hat seems to be a sin#le
system. .lusterin# is often used to increase a system%s availability and for load balancin# on hi#hly0
traffic"ed >eb sites.
.lusterin# al#orithms find #roups of items that are similar. Bor example, clusterin# could be used by
an insurance company to #roup customers accordin# to income, a#e, types of policies purchased and
prior claims experience. It divides a data set so thatrecords +ith similar content are in the same
#roup, and #roups are as different as possible from each other. <ince the cate#ories are unspecified,
this is sometimes referred to as unsupervised learnin#.
5ain strate#ies of clusterin#
1. 2ierarchical clusterin#
2. I0clusterin# !partitionin#$
3. <elf 'r#aniFin# 5aps !<'5$
4. 2ybrids !incremental$
912. Wh+ did I /et a #ockIi*ed%ut!xception?
A. >hen you #et a Hoc"3imed'ut-xception +hile invo"in# a stateful session -*?, one of t+o
thin#s has occurred
8 Cou have \allo+0concurrent0callsM set to true in your +eblo#ic0e(b0(ar.xml descriptor
and your call timed out +hile +aitin# to be processed. 3he timeout used in this case is the
value \trans0timeout0secondsM element of the +eblo#ic0e(b0(ar.xml descriptor or its default
value of 3J seconds.
8 Cou do not have \allo+0concurrent0callsM set to true and you attempt to invo"e a stateful
session bean that is already busy processin# another re)uest. In this case, the second method
call +ill not bloc" and a Hoc"3imed'ut-xception +ill be thro+n immediately.
922. What is the life c+cle of ),-?
3he lifetime of an 5D? instance is controlled by the container. 'nly t+o states exist Does not exist
and 1eady , as illustrated in the follo+in# fi#ure
3he life of an 5D? instance starts +hen the container invo"es ne+Instance!$ on the 5D? class to
create a ne+ instance. 9ext, the container calls set5essa#eDriven.ontext!$ follo+ed by e(b.reate!$
on the instance. 3he bean then enters the 1eady state and is ready to consume messa#es.
>hen a messa#e arrives for the bean, the container invo"es the on5essa#e!$ method of one of the
available instances, passin# a 5essa#e ob(ect in ar#ument. 5essa#e s can be consumed and
processed concurrently by usin# multiple instances of the same type.
3he container invo"es e(b1emove!$ on the bean instance +hen it no lon#er needs the instance. 3he
bean instance can performclean up operations here.
902. Can an entit+ bean be a listener for 6)" *essa/es?
9o. 5essa#e driven beans should be used to consume *5< messa#es.
932. What is !ntit+ -ean. What are the various t+pes of !ntit+ -ean?
-ntity bean represents the real data +hich is stored in the persistent stora#e li"e Database or file
system. Bor example, 3here is a table in Database called .reditXcard. 3his table contains
creditXcardXno,firstXname, lastXname, ssn as colums and there are 1JJ ro+s in the table. 2ere each
ro+ is represented by one instance of the entity bean and it is found by an uni)ue "ey !primary "ey$
creditXcardXno.
3here are t+o types of entity beans.
1$ .ontainer 5ana#ed /ersistence!.5/$
2$ ?ean 5ana#ed /resistence!?5/$
972. What is II%( ?
It is Internet Inter 'b(ect 1esource ?ro"er /rotocl
992. Wh+ donEt stateful session beans have a pool?
<tateful session beans #et instantiated once for each seperate client re)uest and it stores the client
information in it, there is no threadin# concept in -*? hence if there +ill be an instance pool +ill exist
then there is a possiblity of information lea" bet+een different session ob(ects.
therefore there is no concept of instance poolin# in stateful session bean.
9;2. Without usin/ entit+ beans can we do database transactions?
>ithout usin# entity beans +e can do database transactions throu#h <prin#s .<prin# can be used
to confi#ure declarative transaction mana#ement, remote access to your lo#ic usin# 15I or +eb
services, mailin# facilities and various options in persistin# your data to a database
9<2. What is the use of usin/ session facade desi/n pattern in !6-E"?
3here are many uses, important one is to reduce net+or" traffic I you are callin# many -*? from your
<ervlet then this is not advised, because it has to ma"e many net+or" trips, so +hat you do you call a
<tateless session bean and this in turn calls other -*?, since they are in same container there is less
net+or" calls other thin# you can do no+ is you can convert them to H'.AH -*? +hich has not
net+or" calls. 3his increases your server band+idth*. /roblem solver this is #ood for a hi#hly available
system.
9>2. What is the difference between session and entit+ beans? When should I use one or
the other?
An entity bean represents persistent #lobal data from the database: a session bean represents
transient user0specific data that +ill die +hen the user disconnects !ends his session$. Oenerally, the
session beans implement business methods !e.#.?an".transferBunds$ that call entity beans !e.#.
Account.deposit, Account.+ithdra+$
;@2. Is it possible to share an Cttp"ession between a 6"( and !6-? What happens when I
chan/e a value in the Cttp"ession fro* inside an !6-? V
Cou can pass the 2ttp<ession as parameter to an -*? method, only if all ob(ects in session are
serialiFable.3his has to be consider as passed0by0value, that means that itAs read0only in the -*?. If
anythin# is altered from inside the -*?, it +onAt be reflected bac" to the 2ttp<ession of the <ervlet
.ontainer.3he pass0by0reference can be used bet+een -*?s 1emote Interfaces, as they are remote
references. >hile it is possible to pass an 2ttp<ession as a parameter to an -*? ob(ect, it is
considered to be bad practice in terms of ob(ect0oriented desi#n. 3his is because you are creatin# an
unnecessary couplin# bet+een bac"0end ob(ects !-*?s$ and front0end ob(ects !2ttp<ession$. .reate a
hi#her0level of abstraction for your -*?s A/I. 1ather than passin# the +hole, fat, 2ttp<ession !+hich
carries +ith it a bunch of http semantics$, create a class that acts as a value ob(ect !or structure$ that
holds all the data you need to pass bac" and forth bet+een front0end7bac"0end. .onsider the case
+here your -*? needs to support a non 233/0based client. 3his hi#her level of abstraction +ill be
flexible enou#h to support it.
;12.What is !6- role in 62!!?
-*? technolo#y is the core of *2--. It enables developers to +rite reusable and portable server0
side business lo#ic for the *2-- platform.
;22.what are ContainerJ)ana/ed Iransactional attributes ?
9ot <upported
3he bean is not involved in a transaction. If the bean invo"er calls the bean +hile involved in
a transaction, the invo"er%stransaction is suspended, the bean executes, and +hen the bean returns,
the invo"er%s transaction is resumed.
1e)uired
3he bean must be involved in a transaction. If the invo"er is involved in a transaction, the bean uses
the invo"er%s transaction. If the invo"er is not involved in a transaction, the container starts a
ne+ transaction for the bean.
<upports
>hatever transactional state that the invo"er is involved in is used for the bean. If the invo"er has
be#un a transaction, the invo"er%s transaction context is used by the bean. If the invo"er is not
involved in a transaction, neither is the bean.
1e)uires9e+
>hether or not the invo"er is involved in a transaction, this bean starts a ne+ transaction that exists
only for itself. If the invo"er calls +hile involved in a transaction, the invo"er%s transaction is
suspended until the bean completes.
5andatory
3he invo"er must be involved in a transaction before invo"in# this bean. 3he bean uses the
invo"er%s transaction context.
9ever
3he bean is not involved in a transaction. Burthermore, the invo"er cannot be involved in
a transaction +hen callin# the bean. If the invo"er is involved in a transaction, a 1emote-xception is
thro+n
;02.Cow is persistence i*ple*ented in enterprise beans?
/ersistence in -*? is ta"en care of in t+o +ays, dependin# on ho+ you implement your beans
container mana#ed persistence !.5/$ or bean mana#ed persistence !?5/$ Bor .5/, the -*? container
+hich your beans run under ta"es care of the persistence of the fields you have declared to be
persisted +ith the database 0 this declaration is in the deployment descriptor. <o, anytime you modify
a field in a .5/ bean, as soon as the method you have executed is finished, the ne+ data is persisted
to the database by the container. Bor ?5/, the -*? bean developer is responsible for definin# the
persistence routines in the proper places in the bean, for instance, the e(b.reate!$, e(b<tore!$,
e(b1emove!$ methods +ould be developed by the bean developer to ma"e calls to the database. 3he
container is responsible, in ?5/, to call the appropriate method on the bean. <o, if the bean is bein#
loo"ed up, +hen the create!$ method is called on the 2ome interface, then the container is responsible
for callin# the e(b.reate!$ method inthe bean, +hich should have functionality inside for #oin# to the
database and loo"in# up the data.
;32. Are we allowed to chan/e the transaction isolation propert+ in *iddle of a transaction?
9o. Cou cannot chan#e the transaction isolation level in the middle of transaction.
;72. Gor !ntit+ -eans$ What happens to an instance field not *apped to an+ persistent
stora/e$ when the bean is passivated?
3he specification infers that the container never serialiFes an instance of an -ntity bean !unli"e
stateful session beans$. 3huspassivation simply involves movin# the bean from the ready to the
pooled bin. <o +hat happens to the contents of an instance variable is controlled by the
pro#rammer. 1emember that +hen an entity bean is passivated the instance #ets lo#ically
disassociated from itAs remote ob(ect. ?e careful here, as the functionality of passivation7activation for
<tateless <ession, <tateful <ession and -ntity beans is completely different. Bor entity beans the
e(b/assivate method notifies the entity bean that it is bein# disassociated +ith a particular entity prior
to reuse or for dereference.
;92. What is a )essa/e ,riven -ean$ what functions does a *essa/e driven bean have and
how do the+ work in collaboration with 6)"?
5essa#e driven beans are the latest addition to the family of component bean types defined by the
-*? specification. 3he ori#inal bean types include session beans, +hich contain business lo#ic and
maintain a state associated +ith client sessions, and entity beans, +hich map ob(ects to persistent
data. 5essa#e driven beans +ill provide asynchrony to -*? based applications by actin# as *5<
messa#e consumers. A messa#e bean is associated +ith a *5< topic or )ueue and receives *5<
messa#es sent by -*? clients or other beans. 4nli"e entity beans and session beans, messa#e beans
do not have home or remote interfaces. Instead, messa#e driven beans are instantiated by the
container as re)uired. Hi"e stateless session beans, messa#e beans maintain no client0specificstate,
allo+in# the container to optimally mana#e a pool of messa#e0bean instances. .lients send *5<
messa#es to messa#e beans in exactly the same manner as they +ould send messa#es to any other
*5< destination. 3his similarity is a fundamental desi#n #oal of the *5< capabilities of the ne+
specification. 3o receive *5< messa#es, messa#e driven beans implement the
(avax.(ms.5essa#eHistener interface, +hich defines a sin#le on5essa#e!$ method. >hen a messa#e
arrives, the container ensures that a messa#e bean correspondin# to the messa#e topic7)ueue exists
!instantiatin# it if necessary$, and calls its on5essa#e method passin# the clientAs messa#e as the
sin#le ar#ument. 3he messa#e beanAs implementation of this method contains thebusiness lo#ic
re)uired to process the messa#e. 9ote that session beans and entity beans are not allo+ed to function
as messa#e beans.
;;2.What is the advanta/e of puttin/ an !ntit+ -ean instance fro* the :ead+ "tate to
(ooled state?
3he idea of the /ooled <tate is to allo+ a container to maintain a pool of entity beans that has been
created, but has not been yet synchroniFed or assi#ned to an -*?'b(ect. 3his mean that the instances
do represent entity beans, but they can be used only for servin# 2ome methods !create or find?y$,
since those methods do not relay on the specific values of the bean. All these instances are, in fact,
exactly the same, so, they do not have meanin#ful state. *on 3horarinsson has also added It can be
loo"ed at it this +ay If no client is usin# an entity bean of a particular type there is no need for cachi#
it !the data is persisted in the database$. 3herefore, in such cases, the container +ill, after some time,
move the entity bean from the 1eady <tate to the /ooled state to save memory. 3hen, to save
additional memory, the container may be#in movin# entity beans from the /ooled <tate to the Does
9ot -xist <tate, because even thou#h the beanAs cache has been cleared, the bean still ta"es up some
memory (ust bein# in the /ooled <tate.
;<2. What is "ession -ean?
3he entity bean is used to represent data in the database. It provides an ob(ect0oriented interface to
data that +ould normally be accessed by the *D?. or some other bac"0end A/I. 5ore than that, entity
beans provide a component model that allo+s bean developers to focus their attention on
the business lo#ic of the bean, +hile the container ta"es care of mana#in# persistence,transactions,
and access control.
3here are t+o basic "inds of entity beans container0mana#ed ersistence !.5/$ andbean0mana#ed
persistence !?5/$.
.ontainer0mana#ed persistence beans are the simplest for the bean developer to create and the most
difficult for the -*? server to support. 3his is because all the lo#ic for synchroniFin# the
bean%s state +ith the database is handled automatically by the container. 3his means that the
bean developer doesn%t need to +rite any data access lo#ic, +hile the -*? server is
supposed to ta"e care of all the persistence needs automatically. >ith .5/, the container mana#es
the persistence of the entity bean. Lendor tools are used to map the entity fields to the database and
absolutely no database access code is +ritten in the beanclass.
3he bean0mana#ed persistence !?5/$ enterprise bean mana#es synchroniFin# its state +ith the
database as directed by the container. 3he bean uses a database A/I to read and +rite its fields to the
database, but the container tells it +hen to do each synchroniFation operation and mana#es the
transactions for the bean automatically. ?ean0mana#ed persistence #ives the beandeveloper the
flexibility to perform persistence operations that are too complicated for the container or to use a data
source that is not supported by the container.
;>2.If *+ session bean with sin/le *ethod insert record into 2 entit+ beans$ how can I
know that the process is done in sa*e transaction 1the attributes for these beans are
:eDuired2
It depends on the transaction attribute of the session bean also. Cou have to set the transaction
attribute of the session bean either to 1e)uired or 1e)uires9e+.
<@2.Can i *ap *ore than one table in a C)(?
9o, you cannot map more than one table to a sin#le .5/ -ntity ?ean. .5/ has been, in fact, desi#ned
to map a sin#le table.
<12. ,ifference between "ession-ean re*ove12 and !ntit+-ean re*ove12 *ethod?
<ession?ean remove!$ inform the container of your loss of interest in this bean. .ontainer +ill
remove the instance.
-ntity?ean remove!$ delete an entity bean +ithout first instantiatin# it. Delete the ro+ of the table
usin# mentioned primary "ey.
<22. ,oes each stateless session bean have its own !6-%bject?
3his is container specific as it is responsible for hadlin# the beans. 3here may be a 19 or 59
relationship bet+een -*?'b(ect and the session ?ean.
"truts GAQs
Q 1. What is )8C?
5odel0Lie+0.ontroller !5L.$ is a desi#n pattern put to#ether to help control chan#e. 5L. decouples
interface from business lo#ic and data.
)odel 3he model contains the core of the application%s functionality. 3he model enca psulates the
state of the application. <ometimes the only functionality it contains is state. It "no+s nothin# about
the vie+ or controller.
8iew 3he vie+ provides the presentation of the model. It is the look of the application. 3he vie+ can
access the model #etters, but it has no "no+led#e of the setters. In addition, it "no+s nothin# about
the controller. 3he vie+ should be notified +hen chan#es to the model occur.
Controller 3he controller reacts to the user input. It creates and sets the model.
Q 2. What is a fra*ework?
Brame+or" is made up of the set of classes +hich allo+ us to use a library in a best possible +ay for a
specific re)uirement.
Q 0. What is "truts fra*ework?
<truts frame+or" is an open0source frame+or" for developin# the +eb applications in *ava -- , based
on 5L.02 architecture. It uses and extends the *ava <ervlet A/I. <truts is robust architecture and can
be used for the development of application
of any siFe. <truts frame+or" ma"es it much easier to desi#n scalable, reliable >eb applications +ith
*ava. <truts provides its o+n .ontroller component and inte#rates +ith other technolo#ies to provide
the 5odel and the Lie+. Bor the 5odel, <truts can interact +ith standard data access technolo#ies,
li"e *D?. and -*?, as +ell as most any third0party pac"a#es, li"e 2ibernate, i?A3I<, or 'b(ect
1elational ?rid#e. Bor the Lie+, <truts +or"s +ell +ith *ava<erver /a#es , includin# *<3H and *<B, as
+ell as Lelocity3emplates, ^<H3, and other presentation systems.
Q 3. What is 6akarta "truts Gra*eworkG
*a"arta <truts is open source implementation of 5L. !5odel0Lie+0.ontroller$ pattern for the
development of +eb based applications. *a"arta <truts is robust architecture and can be used for the
development of application of any siFe. <truts frame+or" ma"es it much easier to desi#n scalable,
reliable >eb applications +ith *ava.
Q 7. What is Action"ervlet?
3he class or#.apache.struts.action.Action<ervlet is the called the Action<ervlet. In the the *a"arta
<truts Brame+or" this class plays the role of controller. All the re)uests to the server
#oes throu#h the controller. .ontroller is responsible for handlin# all the re)uests.
Q 9. What is role of Action"ervlet?
Action<ervlet performs the role of .ontroller
/rocess user re)uests
Determine +hat the user is tryin# to achieve accordin# to the re)uest
/ull data from the model !if necessary$ to be #iven to the appropriate vie+,
<elect the proper vie+ to respond to the user
Dele#ates most of this #runt +or" to Action classes
Is responsible for initialiFation and clean0up of resources
Q ;. What is Action Class?
Any (ava class +hich extends from or#.apache.struts.action.Action is called Action class. 3he Action is
part of the controller. 3he purpose of Action .lass is to translate the 2ttp<ervlet1e)uest to
the business lo#ic. 3o use the Action, +e need to <ubclass and over+rite the execute!$ method. 3he
Action<ervlet !commad$ passes the parameteriFed class to Action Borm usin# the execute!$ method.
3here should be no database interactions in the action. 3he action should receive the re)uest,
call business ob(ects !+hich then handle database, or interface +ith *2--, etc$ and then determine
+here to #o next. -ven better, the business ob(ects could be handed to the action at runtime !Io.
style$ thus removin# any dependencies on the model. 3he return type of the execute method is
ActionBor+ard +hich is used by the <truts Brame+or" to for+ard the re)uest to the file as per the
value of the returned ActionBor+ard ob(ect..
Q <. Write code of an+ Action Class?
packa/e com.dur#asoft:
i*port (avax.servlet.http.8:
i*port or#.apache.struts.action.8:
public class 3estAction extends Action
6
public ActionBor+ard execute!Action5appin# mappin#, ActionBorm form,
2ttp<ervlet1e)uest re)uest,2ttp<ervlet1esponse response$ throws -xception
6
return mappin#.findBor+ard!=success=$:
;
;
Q >. What is ActionGor*?
Any (ava class +hich extends from or#.apache.struts.action.ActionBorm is called ActionBorm.
An ActionBorm is also called *ava?ean. ActionBorm maintains the session state for +eb application and
the ActionBorm ob(ect is automatically populated on the server side +ith data entered from a form on
the client side.
Q1@. What is "truts 8alidator Gra*ework?
<truts Brame+or" provides the functionality to validate the form data. It can be use to validate the
data on the users bro+ser as +ell as on the server side. <truts Brame+or" emits the (ava scripts and
it can be used validate the form data on the client bro+ser. <erver side validation of form can be
accomplished by sub classin# your Brom ?ean +ith ,+na8alidatorGor* class.
3he Lalidator frame+or" +as developed by David >interfeldt as third0party add0on to <truts. 9o+
the Lalidator frame+or" is a part of *a"arta .ommons pro(ect and it can be used +ith or +ithout
<truts. 3he Lalidator frame+or" comes inte#rated +ith the <truts Brame+or" and can be used +ithout
doin# any extra settin#s.

Q11. Cow +ou will displa+ validation fail errors on jsp pa/e?
Bollo+in# ta# displays all the errors
\htmlerrors7M

Q12. What is :eDuest(rocessor?
3he controller is responsible for interceptin# and translatin# user input into actions to be performed by
the model. 3he controller is responsible for selectin# the next vie+ based on user input and
the outcome of model operations. 3he .ontroller receives the re)uest from the bro+ser, invo"e
a business operation and coordinatin# the vie+ to return to the client.3he controller is implemented by
a (ava servlet, this servlet is centraliFed point of control for the +eb application. In struts frame+or"
the controller responsibilities are implemented by several different components li"e
3he Action<ervlet .lass
3he 1e)uest/rocessor .lass
3he Action .lass
3he Action<ervlet extends the javax.servlet.http.http"ervlet class. 3he Action<ervlet class is
not abstract and therefore can be used as a concrete controller by your application.
3he controller is implemented by the Action<ervlet class. All incomin# re)uests are mapped to the
central controller in thedeployment descriptor as follo+s.
\servletM
\servlet0nameMaction\7servlet0nameM
\servlet0classMor#.apache.struts.action.Action<ervlet\7servlet0classM
\7servletM
All re)uest 41Is +ith the pattern 8.do are mapped to this servlet in the deployment descriptor as
follo+s.
\servlet0mappin#M
\servlet0nameMaction\7servlet0nameM
\url0patternM8.do\7url0patternM
\servlet0mappin#M
A re)uest 41I that matches this pattern +ill have the follo+in# form.
http77localhostNJNJ7mycontext7action9ame.do
3he precedin# mappin# is called extension mappin#, ho+ever, you can also specify path mappin#
+here a pattern ends +ith 78 as sho+n belo+.
\servlet0mappin#M
\servlet0nameMaction\7servlet0nameM
\url0patternM7do78\7url0patternM
\url0patternM8.do\7url0patternM
A re)uest 41I that matches this pattern +ill have the follo+in# form.
http77localhostNJNJ7mycontext7do7actionX9ame 3he class
or#.apache.struts.action.re)uest/rocessor process the re)uest from the controller. Cou can sublass
the 1e)uest/rocessor +ith your o+n version and modify ho+ the re)uest is processed.
'nce the controller receives a client re)uest, it dele#ates the handlin# of the re)uest to a helper class.
3his helper "no+s ho+ to execute the business operation associated +ith the re)uested action. In the
<truts frame+or" this helper class is descended of or#.apache.struts.action.Action class. It acts as a
brid#e bet+een a client0side user action and business operation. 3he Action classdecouples the client
re)uest from the business model. 3his decouplin# allo+s for more than one0to0one mappin# bet+een
the user re)uest and an action. 3he Action class also can perform other functions such as
authoriFation, lo##in# before invo"in# businessoperation. the <truts Action class contains several
methods, but most important method is the execute!$ method.
public ActionBor+ard execute!Action5appin# mappin#, ActionBorm form, 2ttp<ervlet1e)uest re)uest,
2ttp<ervlet1esponse response$ thro+s -xception
3he execute!$ method is called by the controller +hen a re)uest is received from a client. 3he
controller creates an instance of the Action class if one doesnGt already exist. 3he strut frame+or" +ill
create only a sin#le instance of each Action class in your application.
Action are mapped in the struts confi#uration file and this confi#uration is loaded into memory at
startup and made available to the frame+or" at runtime. -ach Action element is represented in
memory by an instance of the or#.apache.struts.action. Action5appin# class. 3he Action5appin#
ob(ect contains a path attribute that is matched a#ainst a portion of the 41I of the incomin# re)uest.
\actionM
pathT =7somere)uest=
typeT=com.somepac"a#e.someAction=
scopeT=re)uest=
nameT=someBorm=
validateT=true=
inputT=some(sp.(sp=
\for+ard nameT=<uccess= pathT=7action7xys= redirectT=true=7M
\for+ard nameT=Bailure= pathT=7some(sp.(sp= redirectT=true=7M
\7actionM
'nce this is done the controller should determine +hich vie+ to return to the client. 3he execute
method si#nature in Action class has a return type or#.apache. struts.action.ActionBor+ard class. 3he
ActionBor+ard class represents a destination to +hich the controller may send control once an action
has completed. Instead of specifyin# an actual *</ pa#e in the code, you can declaratively associate
as action for+ard throu#h out the application. 3he action for+ard are specified in the confi#uration file.
\actionM
pathT =7somere)uest=
typeT=com.somepac"a#e.someAction=
scopeT=re)uest=
nameT=someBorm=
validateT=true=
inputT=some(sp.(sp=
\for+ard nameT=<uccess= pathT=7action7xys= redirectT=true=7M
\for+ard nameT=Bailure= pathT=7some(sp.(sp= redirectT=true=7M
\7actionM
3he action for+ard mappin#s also can be specified in a #lobal section, independent of any specific
action mappin#.
\#lobal0for+ardsM
\for+ard nameT=<uccess= pathT=7action7some(sp.(sp= 7M
\for+ard nameT=Bailure= pathT=7someother(sp.(sp= 7M
\7#lobal0for+ardsM
Q10. Cow +ou will handle exceptions in "truts?
In <truts you can handle the exceptions in t+o +ays
a2 ,eclarative !xception Candlin/ Cou can either define #lobal exception handlin# ta#s in your
struts0confi#.xml or define the exception handlin# ta#s +ithin
\actionM..\7actionM ta#.
!xa*ple
\exception
"eyT=database.error.duplicate=
pathT=74ser-xists.(sp=
typeT=myban".account.Duplicate4ser-xception=7M
b2 (ro/ra**atic !xception Candlin/ 2ere you can use try6;catch6; bloc" to handle the
exception.
Q13. What are the different kinds of actions in "truts?
3he different "inds of actions in <truts are
Bor+ardAction, IncludeAction, DispatchAction, Hoo"upDispatchAction, <+itchAction
Q17. What is ,ispatchAction?
3he DispatchAction class is used to #roup related actions into one class. 4sin# this class, you can
have a method for each lo#ical action compared than a sin#le execute method. 3he DispatchAction
dispatches to one of the lo#ical actions represented by the methods. It pic"s a method to invo"e
based on an incomin# re)uest parameter. 3he value of the incomin# parameter is the name of the
method that the DispatchAction +ill invo"e.
Q19. Cow to use ,ispatchAction?
3o use the DispatchAction, follo+ these steps
1. .reate a class that extends DispatchAction !instead of Action$
2. In a ne+ class, add a method for every function you need to perform on the service V 3he
method has the same si#nature as the execute!$ method of an Action class.
3. Do not override execute!$ method V ?ecause DispatchAction class itself provides execute!$
method.
4. Add an entry to struts0confi#.xml
Q1;. What is #ookup,ispatchAction?
3he Hoo"upDispatchAction is a subclass of DispatchAction. It does a reverse loo"up on the resource
bundle to #et the "ey and then #ets the method +hose name is associated +ith the "ey into the
1esource ?undle.
Q1<. What is the use of #ookup,ispatchAction?
Hoo"upDispatchAction is useful if the method name in the Action is not driven by its name in the front
end, but by the Hocale independent "ey into the resource bundle. <ince the "ey is al+ays the same,
the Hoo"upDispatchAction shields your application from the side effects of I1N9.
Q1>. What is difference between #ookup,ispatchAction and ,ispatchAction?
3he difference bet+een Hoo"upDispatchAction and DispatchAction is that the actual method that #ets
called in Hoo"upDispatchAction is based on a loo"up of a "ey value instead of specifyin# the method
name directly.
Q2@. What is "witchAction?
3he <+itchAction class provides a means to s+itch from a resource in one module to another resource
in a different module. <+itchAction is useful only if you have multiple modules in your <truts
application. 3he <+itchAction class can be used as is, +ithout extendin#.
Q21. What if SactionH ele*ent has SforwardH declaration with sa*e na*e as /lobal
forward?
In this case the #lobal for+ard is not used. Instead the \actionM elementAs \for+ardM ta"es
precendence.
Q22. What is difference between ActionGor* and ,+naActionGor*?
An ActionBorm represents an 235H form that the user interacts +ith over one or more pa#es. Cou +ill
provide properties to hold the state of the form +ith #etters and setters to access them. >hereas,
usin# DynaActionBorm there is no need of providin# properties to hold the state. Instead these
properties and their type are declared in the struts0confi#.xml.
3he DynaActionBorm bloats up the <truts confi# file +ith the xml based definition. 3his #ets annoyin#
as the <truts .onfi# file #ro+ lar#er.
3he DynaActionBorm is not stron#ly typed as the ActionBorm. 3his means there is no compile time
chec"in# for the form fields. Detectin# them at runtime is painful and ma"es you #o throu#h
redeployment.
ActionBorm can be cleanly or#aniFed in pac"a#es as a#ainst the flat or#aniFation in the <truts .onfi#
file.
ActionBorm +ere desi#ned to act as a Bire+all bet+een 233/ and the Action classes, i.e. isolate and
encapsulate the 233/ re)uest parameters from direct use in Actions. >ith DynaActionBorm, the
property access is no different than usin# re)uest.#et /arameter! .. $.
DynaActionBorm construction at runtime re)uires a lot of *ava 1eflection !Introspection$
machinery that can be avoided.
Q20. What is the life c+cle of ActionGor*?
3he lifecycle of ActionBorm invo"ed by the 1e)uest/rocessor is as follo+s
1etrieve or .reate Borm ?ean associated +ith Action
=<tore= Borm?ean in appropriate scope !re)uest or session$
1eset the properties of the Borm?ean
/opulate the properties of the Borm?ean
Lalidate the properties of the Borm?ean
/ass Borm?ean to Action
Q23.What are the i*portant ta/s of strutsJconfi/.x*l ?
\struts0confi#M
\]00 TTTTTTTTTT Borm ?ean Definitions TTTTTTTTTTTT 00M
\form0beansM
\form0bean nameT=lo#in= typeT= Ho#inBorm= 7M
\7form0beansM
\]00 TTTTTTTTTT Olobal Bor+ard Definitions TTTTTTTTT 00M
\#lobal0for+ardsM
\7#lobal0for+ardsM
\]00 TTTTTTTTTT Action 5appin# Definitions TTTTTTTT 00M
\action0mappin#sM
\action
pathT=7lo#in=
typeT=Ho#inAction= M
\7actionM
\7action0mappin#sM
\]00 TTTTTTTTTT /roperties Definitions TTTTTTTTTTTT 00M
\messa#e0resources parameterT=5essa#e1esources= 7M
\]00 TTTTTTTTTT Lalidator frame+or" Definitions TTTTTTTTTTTT 00M
\plu#0in class9ameT=or#.apache.struts.validator.Lalidator/lu#In=M
\set0property
propertyT=pathnames=
valueT=7or#7apache7struts7validator7validator0rules.xml,
7>-?0I9B7validation.xml=7M
\7plu#0inM
\7struts0confi#M
Q27. What are the core classes of the "truts Gra*ework?
A .ore classes of <truts Brame+or" are ActionBorm, Action, Action5appin#, Action Bor+ard,
Action<ervlet etc.
Q29. What is action *appin/s?
An action mappin# is a confi#uration file entry that, in #eneral, associates an action name +ith
an action. An action mappin# can contain a reference to a form bean that the action can use, and can
additionally define a list of local for+ards that is visible only to this action.
Q2;. ,escribe validate12 and reset12 *ethods ?
validate 12 and reset12 methods defined inActionBorm class.
validate.0 4sed to validate properties after they have been populated: .alled before Borm?ean is
handed to Action. 1eturns a collection of Action5essa#e as Action-rrors. Bollo+in# is the method
si#nature for the validate!$ method.
public Action-rrors validate!Action5appin# mappin#, 2ttp<ervlet1e)uest re)uest$
reset.0 reset!$ method is called by <truts Brame+or" +ith each re)uest that uses the defined
ActionBorm. 3he purpose of this method is to reset all of the ActionBorm%s data members prior to the
ne+ re)uest values bein# set.
public void reset!$ 6;

Q2<. ?ive the ,etails of M)# files used in 8alidator Gra*ework?
3he Lalidator Brame+or" uses t+o ^5H confi#uration files validatorJrules.x*l and validation.x*l.
3he validatorJrules.x*ldefines the standard validation routines, these are reusable and used
in validation.x*l. to define the form specific validations. 3he validation.x*l defines the validations
applied to a form bean.
Q2>. Cow +ou will enable frontJend validation based on the x*l in validation.x*l?
3he \html(avascriptM ta# to allo+ front0end validation based on the xml in validation.xml. Bor
example the code \html(avascript form9ameT=lo#onBorm= dynamic*avascriptT=true=
static*avascriptT=true= 7M #enerates the client side (ava script for the form =lo#onBorm= as defined in
the validation.xml file. 3he \html(avascriptM +hen added in the (sp file #enerates the client site
validation script.
Q0@. What is the difference between perfor*12 and execute12 *ethods?
perform!$ method defined in <truts 1.J. but it is +as deprecated in the <truts Lersion 1.1. In <truts
1.x, Action.perform!$ is the method called by the Action<ervlet. 3his is typically +here your business
lo#ic resides, or at least the flo+ control to your *ava?eans and -*?s that handle your business lo#ic.
As +e already mentioned, to support declarative exception handlin#, the method si#nature chan#ed in
perform. 9o+ execute (ust thro+s -xception. Action.perform!$ is no+ deprecated: ho+ever, the <truts
v1.1 Action<ervlet is smart enou#h to "no+ +hether or not it should call perform or execute in the
Action, dependin# on +hich one is available.
Q01. What are the various "truts ta/ libraries?
<truts is very rich frame+or" and it provides very #ood and user friendly +ay to develop +eb
application forms. <truts provide many ta# libraries to ease the development of +eb applications.
3hese ta# libraries are
V -ean ta/ librar+ 0 3a#s for accessin# *ava?eans and their properties.
V CI)# ta/ librar+ 0 3a#s to output standard 235H, includin# forms, text boxes, chec"boxes, radio
buttons etc..
V #o/ic ta/ librar+ 0 3a#s for #eneratin# conditional output, iteration capabilities and flo+
mana#ement
V Iiles or Ie*plate ta/ librar+ 0 Bor the application usin# tiles
V 'ested ta/ librar+ 0 Bor usin# the nested beans in the application
Q02. What are the difference between Sbean*essa/eH and SbeanwriteH?
Sbean*essa/eH 3his ta# is used to output locale0specific text !from the properties files$ from a
5essa#e1esources bundle.
SbeanwriteH 3his ta# is used to output property values from a bean. \bean+riteM is a commonly
used ta# +hich enables the pro#rammers to easily present the data.
Q00. What are difference between Action!rrors and Action)essa/e?
Action)essa/e A class that encapsulates messa#es. 5essa#es can be either #lobal or they are
specific to a particular bean property.
-ach individual messa#e is described by an Action5essa#e ob(ect, +hich contains a messa#e "ey !to
be loo"ed up in an appropriate messa#e resources database$, and up to four placeholder ar#uments
used for parametric substitution in the resultin# messa#e.
Action!rrors A class that encapsulates the error messa#es bein# reported by the validate!$
method of an ActionBorm. Lalidation errors are either #lobal to the entire ActionBorm bean they are
associated +ith, or they are specific to a particular bean property !and, therefore, a particular input
field on the correspondin# form$.
Q03. What is the use of GorwardAction?
3he Bor+ardAction class is useful +hen youAre tryin# to inte#rate <truts into an existin# application
that uses <ervlets to perform business lo#ic functions. Cou can use this class to ta"e advanta#e of the
<truts controller and its functionality, +ithout havin# to re+rite the existin# <ervlets. 4se
Bor+ardAction to for+ard a re)uest to another resource in your application, such as a <ervlet that
already does business lo#ic processin# or even another *</ pa#e. ?y usin# this predefined action, you
donAt have to +rite your o+n Action class. Cou (ust have to set up the struts0confi# file properly to use
Bor+ardAction.
Q07. What is IncludeAction?
3he IncludeAction class is useful +hen you +ant to inte#rate <truts into an application that uses
<ervlets. 4se the IncludeAction class to include another resource in the response to the re)uest bein#
processed.
Q09. What are the steps need to use ,+naActionGor*?
4sin# a DynaActionBorm instead of a custom subclass of ActionBorm is relatively strai#htfor+ard. Cou
need to ma"e chan#es in t+o places
In struts0confi#.xml chan#e your \form0beanM to be an or#.apache.struts.action.Dyna ActionBorm
instead of some subclass of ActionBorm
\form0bean nameT=lo#inBorm=
typeT=or#.apache.struts.action.DynaActionBorm= M
\form0property nameT=user9ame= typeT=(ava.lan#.<trin#=7M
\form0property nameT=pass+ord= typeT=(ava.lan#.<trin#= 7M
\7form0beanM
In your Action subclass that uses your form bean
o import or#.apache.struts.action.DynaActionBorm
o do+ncast the ActionBorm parameter in execute!$ to a DynaActionBorm
o access the form fields +ith #et!field$ rather than #etBield!$
Q.0; In struts what happens if *ade an+ chan/es in actionservlet?
3he Action<ervlet plays the role of controller +ich is responsible for handlin# the re)uest and selectin#
the correct Application 5odule and storin# Application.onfi# and 5essa#e1esource bundle in the
re)uest ob(ect.
If +e modify the Action<ervlet the .ontroller may or may not +or" +hat happens that depends on
your modification, Cou have not specify +hether you +ant to create your o+n custom Action<ervlet by
extendin# Action<ervlet and overridin# the methods in it or +hat exactly you +ant to modify.
Cibernate GAQs1
1.what is the advanta/e of Cibernate over jdbc?
3here are so many
1$ 2ibernate is data base independent, your code +ill +or" for all '1A.H-,5y<EH ,<EH<erver etc.
In case of *D?. )uery must be data base specific. <o hibernate based persistance lo#ic is database
independent persistance lo#ic and *D?. based persistance lo#ic is database dependent lo#ic.
2$ As 2ibernate is set of 'b(ects ,
3$ 9o need to learn <EH lan#ua#e.Cou can treat 3A?H- as a 'b(ect . 'nly *ava "no+led#e is need.
In case of *D?. you need to learn <EH.
3$ Dont need Euery tunin# in case of 2ibernate. If you use .riteria Euires in 2ibernate then
hibernate automatically tuned your )uery and return best result +ith performance.
In case of *D?. you need to tune your )ueries.
4$ Cou +ill #et benefit of .ache. 2ibernate support t+o level of cache. Birst level and 2nd level. <o
you can store your data into .ache for better performance.
In case of *D?. you need to implement your (ava cache .
5$ 2ibernate supports Euery cache and It +ill provide the statistics about your )uery and database
status.
*D?. 9ot provides any statistics.
6$ Development fast in case of 2ibernate because you dont need to +rite )ueries
&$ 9o need to create any connection pool in case of 2ibernate. Cou can use c3pJ.
In case of *D?. you need to +rite your o+n connection pool
N$ In the xml file you can see all the relations bet+een tables in case of 2ibernate. -asy readability.
K$ Cou can load your ob(ects on start up usin# laFyTfalse in case of 2ibernate.
*D?. Dont have such support.
1J $ 2ibernate <upports automatic versionin# of ro+s but *D?. 9ot.
2.What is Cibernate?
2ibernate is an open source, li#ht +ei#ht 'b(ect 1elational 5appin# tool to develop the database
independent persistence lo#in in (ava and (2ee based applications.
2ibernate is a pure *ava ob(ect0relational mappin# !'15$ and persistence frame+or" that allo+s you
to map plain old *ava ob(ects to relational database tables usin# !^5H$ confi#uration and mappin#
files. Its purpose is to relieve the developer from a si#nificant amount of relational data persistence0
related pro#rammin# tas"s
0.What is %:) ?
'15 stands for ob(ect7relational mappin#, means providin# the mappin# bet+een class +ith table and
member variables +ith columns is called '15. '15 is the automated persistence of ob(ects in
a *ava application to the tables in a relational database.
3.hat does %:) consists of ?
An '15 solution consists of the follo+in# four pieces
A/I for performin# basic .14D operations
A/I to express )ueries referrin# to classes
Bacilities to specify metadata
'ptimiFation facilities dirty chec"in#,laFy associations fetchin#
7.What are the %:) levels ?
3he '15 levels are
/ure relational !stored procedure.$
Hi#ht ob(ects mappin# !*D?.$
5edium ob(ect mappin#
Bull ob(ect 5appin# !composition,inheritance, polymorphism, persistence by reachability$
.
9.Wh+ do +ou need %:) tools like hibernate?
3he main advanta#e of '15 li"e hibernate is that it can develop the database independent persistence
lo#ic. Apart from this, '15 provides follo+in# benefits
I*proved productivit+
o 2i#h0level ob(ect0oriented A/I
o Hess *ava code to +rite
o 9o <EH to +rite
I*proved perfor*ance
o <ophisticated cachin#
o HaFy loadin#
o -a#er loadin#
I*proved *aintainabilit+
o A lot less code to +rite
I*proved portabilit+
'15 frame+or" #enerates database0specific <EH for you
;.What ,oes Cibernate "i*plif+?
2ibernate simplifies
<avin# and retrievin# your domain ob(ects
5a"in# database column and table name chan#es
.entraliFin# pre save and post retrieve lo#ic
.omplex (oins for retrievin# related items
<chema creation from ob(ect model
<.What is the *ain difference between !ntit+ -eans and Cibernate ?
1$In -ntity ?ean at a time +e can interact +ith only one data ?ase. >here as in 2ibernate +e can able
to establishes the connections to more than 'ne Data ?ase. 'nly thin# +e need to +rite one
more confi#uration file.
2$ -*? need container li"e >eblo#ic, >eb<phare but hibernate don%t nned. It can be run on tomcat.
3$ -ntity ?eans does not support ''/< concepts +here as 2ibernate does.
4$ 2ibernate supports multi level cachein#, +here as -ntity ?eans doesn%t.
5$ In 2ibernate .3/J can be used as a connection pool.
6$ 2ibernate is container independent. -*? not.
>.What are the Core interfaces and classes of Cibernate fra*ework?
3he five core interfaces are used in (ust about every 2ibernate application. 4sin# these interfaces, you
can store and retrieve persistent ob(ects and control transactions.
.onfi#uration class !or#.hibernate.cf# pac"a#e$
<ession interface !or#.hibernate pac"a#e$
<essionBactory interface !or#.hibernate pac"a#e$
3ransaction interface !or#.hibernate pac"a#e$
Euery and .riteria interfaces !or#.hibernate pac"a#e$
1@.What is the /eneral flow of Cibernate co**unication with :,-)"?
3he #eneral flo+ of 2ibernate communication +ith 1D?5< is
Hoad the 2ibernate confi#uration file and create confi#uration ob(ect. It +ill automatically load
all hbm mappin# files because mappin# file can be confi#ured in confi#uration file.
.reate session factory from confi#uration ob(ect
Oet one session from this session factory
.reate 2EH Euery
-xecute )uery to #et list containin# *ava ob(ects.

11.What is the need for Cibernate *appin/ file?


2ibernate mappin# file is used to provides the mappin# bet+een (ava class +ith table member
variables +ith column names of the table. And also +e can confi#ure primary "ey #eneration
al#orithm, relations and so on. 3ypical mappin# file loo" as follo+s

12.What are the i*portant ta/s of hibernate.cf/.x*l?
3his file can be used to provide the database information li"e driverclass name, url, database
usename, database pass+ord, dialect, connection poolin# mappin# file and so on.
Bollo+in# are the important ta#s of hibernate.cf#.xml


10.What role does the "ession interface pla+ in Cibernate?
3he main runtime interface bet+een a *ava application and 2ibernate 3he <ession interface is the
primary interface used by 2ibernate applications. It is a sin#le0threaded, short0lived ob(ect
representin# a conversation bet+een the application and the persistent store. It allo+s you to create
)uery ob(ects to retrieve persistent ob(ects.
3he main function of the <ession is to offer create, read and delete operations for instances of mapped
entity classes. Instances may exist in one of three states
transient: never persistent, not associated +ith any <ession
persistent: associated +ith a uni)ue <ession
detached: previously persistent, not associated +ith any <ession
<ession session T sessionBactory.open<ession!$:
"ession interface role
>raps a *D?. connection
Bactory for 3ransaction
2olds a mandatory !first0level$ cache of persistent ob(ects, used +hen navi#atin# the ob(ect
#raph or loo"in# up ob(ects by identifier
13.What role does the "essionGactor+ interface pla+ in Cibernate?
<essionBactorys are immutable. 3he behaviour of a <essionBactory is controlled by properties supplied
at confi#uration time. 3hese properties are defined on -nvironment.
3he application obtains <ession instances from a <essionBactory. 3here is typically a sin#le
<essionBactory for the +holeapplicationccreated durin# application initialiFation. 3he <essionBactory
caches #enerate <EH statements and other mappin# metadata that 2ibernate uses at runtime. It also
holds cached data that has been read in one unit of +or" and may be reused in a future unit of +or"
Implementors must be threadsafe.
<essionBactory sessionBactory T confi#uration.build<essionBactory!$:
17.What are the *ost co**on wa+s to specif+ the Cibernate confi/uration properties?
3he most common methods of 2ibernate confi#uration are
/ro#rammatic confi#uration
?y usin# set/roperty!0$ method of or#.hibernate.cf#..onfi#uration.
^5H confi#uration !hibernate.cf#.xml$
?y usin# .properties file
?y 4sin# annotaions.!from 2ibernate 3.3 on +ords$
19.Cow do +ou *ap 6ava %bjects with ,atabase tables?
Birst +e need to +rite *ava domain ob(ects !beans +ith setter and #etter$.
>rite hbm.xml, +here +e map (ava class to table and database columns
to *ava class variables.
!xa*ple
\hibernate0mappin#M
\class nameT=com.dur#asoft.-mployee?ean= tableT=-5/H'C--=M
\id nameT[eid[ columeT[id[7M
\property nameT=ename= columnT=9A5-= len#thT=255=
not0nullT=true= typeT=(ava.lan#.<trin#=7M
\property nameT=address= columnT=ADD1= len#thT=255=
not0nullT=true= typeT=(ava.lan#.<trin#=7M
\7classM
\7hibernate0mappin#M
1;.Cow do +ou define seDuence /enerated pri*ar+ ke+ al/orith* in hibernate?
?y usin# \idM, \#eneratorM ta#s +e can confi#ure the primary "ey and primary "ey #eneration
al#orithm.
!xa*ple0
\id nameT=userid= columnT=4<-1XID= typeT=(ava.lan#.Hon#=M
\#enerator classT=se)uence=M
\param nameT=table=M<-EX9A5-\7paramM
\#eneratorM
\7idM
1<.What is co*ponent *appin/ in Cibernate?
A component is an ob(ect saved as a value, not as a reference
A component can be saved directly +ithout needin# to declare interfaces or identifier
properties
1e)uired to define an empty constructor
<hared references not supported
1> . ,ifference between /etCurrent"ession12 and open"ession12 in Cibernate ?
#et.urrent<ession!$
'btains the current session. 3he =current session= refers to a 2ibernate <ession bound by 2ibernate
behind the scenes, to the transaction scope.
A <ession is opened +hen #et.urrent<ession!$ is called for the first time and closed +hen the
transaction ends. It is also flushed automatically before the transaction commits. Cou can call
#et.urrent<ession!$ as often and any+here you +ant as lon# as the transaction runs. 'nly the
<ession that you obtained +ith sf.#et.urrent<ession!$ is flushed and closed automatically.
open<ession!$
If you decide to use mana#e the <ession yourself the #o for sf.open<ession!$ , you have to flush!$ and
close!$ it.
It does not flush and close!$ automatically.
-xample
3ransaction tx Tsession.ber#in3ransaction!$:
<ession session T factory.open<ession!$:
try 6
tx.be#in!$:
77 Do some +or"
session.createEuery!...$:
session.persist!...$:
session.flush!$: 77 -xtra +or" you need to do
tx.commit!$:
;
catch !1untime-xception e$ 6
tx.rollbac"!$:
thro+ e: 77 or display error messa#e
;
finally 6
session.close!$: 77 -xtra +or" you need to do
;
2@.What are the t+pes of Cibernate instance states ?
3hree types of instance states
3ransient 03he instance is not associated +ith any persistence context
/ersistent 03he instance is associated +ith a persistence context
Detached 03he instance +as associated +ith a persistence context +hich has been closed V
currently not associated
21.What are the t+pes of inheritance *odels in Cibernate?
3here are three types of inheritance models in 2ibernate
3able per class hierarchy
3able per subclass
3able per concrete class
22.What is Cibernate Quer+ #an/ua/e 1CQ#2?
2ibernate Euery Han#ua#e is )uery lan#ua#e +hich is used to develop the data independent
)uery lan#ua#e in the application. 3his 2EH )ueries are not related to any database. 2ibernate offers
a )uery lan#ua#e that embodies a very po+erful and flexible mechanism to )uery, store, update, and
retrieve ob(ects from a database. 3his lan#ua#e, the 2ibernate )uery Han#ua#e !2EH$, is an ob(ect0
oriented extension to <EH.
20.What are the wa+s to express joins in CQ#?
2EH provides four +ays of expressin# !inner and outer$ (oins0
An implicit association (oin
An ordinary (oin in the B1'5 clause
A fetch (oin in the B1'5 clause.
A theta-style (oin in the >2-1- clause.
23 . Iransaction with plain 6,-C in Cibernate ?
If you don%t have *3A and don%t +ant to deploy it alon# +ith your application, you +ill usually have to
fall bac" to *D?. transaction demarcation. Instead of callin# the *D?. A/I you better use 2ibernate%s
3ransaction and the built0in session0per0re)uest functionality
3o enable the thread0bound strate#y in your 2ibernate confi#uration
set hibernate.transaction.factoryXclass to or#.hibernate.transaction.*D?.3ransactionBactory
set hibernate.currentXsessionXcontextXclass to thread
<ession session T factory.open<ession!$:
3ransaction tx T null:
try 6
tx T session.be#in3ransaction!$:
77 Do some +or"
session.load!...$:
session.persist!...$:
tx.commit!$: 77 Blush happens automatically
;
catch !1untime-xception e$ 6
tx.rollbac"!$:
thro+ e: 77 or display error messa#e
;
finally 6
session.close!$:
;
27 . What are the /eneral considerations or best practices for definin/ +our Cibernate
persistent classes?
1.Cou must have a default no0ar#ument constructor for your persistent classes and there should be
#et^^^!$and set^^^!$ methods for all your persistable instance variables.
2.Cou should implement the e)uals!$ and hash.ode!$ methods based on your business "ey and it is
important not to use the id field in your e)uals!$ and hash.ode!$ definition if the id field is a surro#ate
"ey !i.e. 2ibernate mana#ed identifier$. 3his is because the 2ibernate only #enerates and sets the
field +hen savin# the ob(ect.
3. It is recommended to implement the <erialiFable interface. 3his is potentially useful if you +ant to
mi#rate around a multi0processor cluster.
4.3he persistent class should not be final because if it is final then laFy loadin# cannot be used by
creatin# proxy ob(ects.
29 . ,ifference between session.update12 and session.lock12 in Cibernate ?
3he session.update method is used to update the persistence ob(ect in the in the database.
3he session.loc"!$ method simply reattaches the ob(ect to the session +ithout chec"in# or updatin#
the database on the assumption that the database in sync +ith the detached ob(ect. It is the best
practice to use either session.update!..$ or session.save'r4pdate!$. 4se session.loc"!$ only if you are
absolutely sure that the detached ob(ect is in sync +ith your detached ob(ect or if it does not matter
because you +ill be over+ritin# all the columns that +ould have chan#ed later on +ithin the same
transaction.
2;.What are the Collection t+pes in Cibernate ?
<et
Hist
Array
5ap
?a#
2<.What is the difference between sorted and ordered collection in hibernate?
sorted collection vs. order collection 0
sorted collection
order collection
A sorted collection is sortin# a collection by utiliFin#
the sortin# features provided by the *ava collections
frame+or". 3he sortin# occurs in the memory of
*L5 +hich runnin# 2ibernate, after the data bein#
read from database usin# (ava comparator.
'rder collection is sortin# a collection by
specifyin# the order0by clause for sortin# this
collection +hen retrieval.
If your collection is not lar#e, it +ill be more
efficient +ay to sort it.
If your collection is very lar#e, it +ill be more
efficient +ay to sort it .
2>.What are the wa+s to express joins in CQ#?
2EH provides four +ays of expressin# !inner and outer$ (oins0
An implicit association (oin
An ordinary (oin in the B1'5 clause
A fetch (oin in the B1'5 clause.
A theta-style (oin in the >2-1- clause.
0@.What do +ou *ean b+ 'a*ed W "Q# Duer+?
9amed <EH )ueries are defined in the mappin# xml document and called +herever re)uired.
!xa*ple
\s)l0)uery name T =empdetails=M
\return aliasT=emp= classT=com.dur#asoft.-mployee=7M
<-H-.3 emp.-5/XID A< 6emp.empid;,
emp.-5/XADD1-<< A< 6emp.address;,
emp.-5/X9A5- A< 6emp.name;
B1'5 -mployee -5/ >2-1- emp.9A5- HII- name
\7s)l0)ueryM
Invo"e 9amed Euery
Hist people T session.#et9amedEuery!=empdetails=$
.set<trin#!=3om?rady=, name$
.set5ax1esults!5J$
.list!$:
31.2o+ do you invo"e <tored /roceduresG
\s)l0)uery nameT=selectAll-mployeesX</= callableT=true=M
\return aliasT=emp= classT=employee=M
\return0property nameT=empid= columnT=-5/XID=7M
\return0property nameT=name= columnT=-5/X9A5-=7M
\return0property nameT=address= columnT=-5/XADD1-<<=7M
6 G T call selectAll-mployees!$ ;
\7returnM
\7s)l0)ueryM
02.!xplain Criteria A(I
3he interface or#.hibernate..riteria represents a )uery a#ainst a particular persistent class. 3he
<ession is a factory for .riteria instances. .riteria is a simplified A/I for retrievin# entities by
composin# .riterion ob(ects. 3his is a very convenient approach for functionality li"e =search= screens
+here there is a variable number of conditions to be placed upon the result set.
!xa*ple
Hist employees T session.create.riteria!-mployee.class$
.add!1estrictions.li"e!=name=, =aY=$ $
.add!1estrictions.li"e!=address=, =?oston=$$
.add'rder!'rder.asc!=name=$ $
.list!$:
00.WhatXs the difference between load12 and /et12?
load!$
#et!$
'nly use the load!$ method if you are sure that the
ob(ect exists.
If you are not sure that the ob(ect exists, then
use one of the #et!$ methods.
load!$ method +ill thro+ an exception if the uni)ue id
is not found in the database.
#et!$ method +ill return null if the uni)ue id is
not found in the database.
load!$ (ust returns a proxy by default and database
+onAt be hit until the proxy is first invo"ed.
#et!$ +ill hit the database immediately.
03.What is the difference between and *er/e and update ?
4se update!$ if you are sure that the session does not contain an already persistent instance +ith the
same identifier, and mer#e!$ if you +ant to mer#e your modifications at any time +ithout
consideration of the state of the session.
07.,efine cascade and inverse option in oneJ*an+ *appin/?
cascade 0 enable operations to cascade to child entities.
cascadeT=allenoneesave0updateedeleteeall0delete0orphan=
inverse 0 mar" this collection as the =inverse= end of a bidirectional association.
inverseT=trueefalse=
-ssentially =inverse= indicates +hich end of a relationship should be i#nored, so +hen persistin# a
parent +ho has a collection of children, should you as" the parent for its list of children, or as" the
children +ho the parents areG
09.,efine CibernateIe*plate?
or#.sprin#frame+or".orm.hibernate.2ibernate3emplate is a helper class +hich provides different
methods for )ueryin#7retrievin# data from the database. It also converts chec"ed 2ibernate-xceptions
into unchec"ed DataAccess-xceptions.
0;.What are the benefits does CibernateIe*plate provide?
3he benefits of 2ibernate3emplate are
2ibernate3emplate, a <prin# 3emplate class simplifies interactions +ith 2ibernate <ession.
.ommon functions are simplified to sin#le method calls.
<essions are automatically closed.
-xceptions are automatically cau#ht and converted to runtime exceptions.
0<. Cow do +ou switch between relational databases without code chan/es?
4sin# 2ibernate <EH Dialects , +e can s+itch databases. 2ibernate +ill #enerate appropriate h)l
)ueries based on the dialect defined.
0>.If +ou want to see the Cibernate /enerated "Q# state*ents on console$ what should we
do?
?y usin# Zsho+Xs)l[ property of the hibernate confi#uration file
In 2ibernate confi#uration file set as follo+s
\property nameT=sho+Xs)l=Mtrue\7propertyM
3@.What are derived properties?
3he properties that are not mapped to a column, but calculated at runtime by evaluation of an
expression are called derived properties. 3he expression can be defined usin# the formula attribute of
the element.
31.,efine cascade and inverse option in oneJ*an+ *appin/?
cascade 0 enable operations to cascade to child entities.
cascadeT=allenoneesave0updateedeleteeall0delete0orphan=
inverse 0 mar" this collection as the =inverse= end of a bidirectional association.
inverseT=trueefalse=
-ssentially =inverse= indicates +hich end of a relationship should be i#nored, so +hen persistin# a
parent +ho has a collection of children, should you as" the parent for its list of children, or as" the
children +ho the parents areG
32 . !xplain about transaction file?
3ransactions denote a +or" file +hich can save chan#es made or revert bac" the chan#es. A
transaction can be started by session.be#in3ransaction!$ and it uses *D?. connection, .'1?A or *3A.
>hen this session starts several transactions may occur.
30 . ,ifference between session.save12 $ session.save%r&pdate12 and session.persist12?
All methods are used to store the data in to database
session.save!$ save!$ method u<ave does an insert and +ill fail if the primary "ey is already
persistent.
session.save'r4pdate!$ save'r4pdate!$ insert the data in the database if that primary "ey data not
available and it update the data if primary "ey data not availabt
session.persist!$ it is the same li"e session.save!$. ?ut session.save!$ return <erialiFable ob(ect but
session.persist!$ return void.
Bor -xample
if you do 0
<ystem.out.println!session.save!)uestion$$:
3his +ill print the #enerated primary "ey.
if you do 0
<ystem.out.println!session.persist!)uestion$$:
.ompile time error because session.persist!$ return void.
33 . !xplain about the id field?
3his id field is used to confi#ure the primary "ey in the mappin# file, and also +e
can confi#ure primary "ey #eneration al#orithm.
37.What is the use of d+na*icJinsert and d+na*icJupdate attributes in a class *appin/?
.riteria is a simplified A/I for retrievin# entities by composin# .riterion ob(ects. 3his is a very
convenient approach for functionality li"e =search= screens +here there is a variable number of
conditions to be placed upon the result set.
dynamic0update !defaults to false$ <pecifies that 4/DA3- <EH should be #enerated at
runtime and contain only those columns +hose values have chan#ed
dynamic0insert !defaults to false$ <pecifies that I9<-13 <EH should be #enerated at runtime
and contain only the columns +hose values are not null.
39.What is auto*atic dirt+ checkin/?
Automatic dirty chec"in# is a feature that saves us the effort of explicitly as"in# 2ibernate to update
the database +hen +e modify the state of an ob(ect inside a transaction.
3;.What are Callback interfaces?
.allbac" interfaces allo+ the application to receive a notification +hen somethin# interestin# happens
to an ob(ectcfor example, +hen an ob(ect is loaded, saved, or deleted. 2ibernate applications don%t
need to implement these callbac"s, but they%re useful for implementin# certain "inds of #eneric
functionality.
3<.What is Cibernate prox+?
3he proxy attribute enables laFy initialiFation of persistent instances of the class. 2ibernate +ill initially
return .OHI? proxies +hich implement the named interface. 3he actual persistent ob(ect +ill be loaded
+hen a method of the proxy is invo"ed.
3>.Cow can Cibernate be confi/ured to access an instance variable directl+ and not throu/h
a setter *ethod ?
?y mappin# the property +ith accessT=field= in 2ibernate metadata. 3his forces hibernate to bypass
the setter method and access the instance variable directly +hile initialiFin# a ne+ly loaded ob(ect.
7@.Cow can a whole class be *apped as i**utable?
5ar" the class as mutableT=false= !Default is true$,. 3his specifies that instances of the class are !not$
mutable. Immutable classes, may not be updated or deleted by the application.
71 . !xplain about transparent persistence of Cibernate?
3ransparent persistence is provided for /lain old *ava ob(ects or /'*'s. Bor proper functionin# of the
applications importance should be #iven to the methods e)uals !$ and hash .ode methods !$. It has a
re)uirement +hich should be strictly follo+ed in the applications +hich is a no0ar#ument constructor.
72 . !xplain about the dirt+ checkin/ feature of Cibernate?
Dirty chec"in# feature of the 2ibernate allo+s users or developers to avoid time
consumin# data base +rite actions. 3his feature ma"es necessary updations and chan#es to the fields
+hich re)uire a chan#e, remainin# fields are left unchan#ed or untouched.
70 . What is the effect when a transient *apped object is passed onto a "essions save?
>hen a <essions save !$ is passed to a transient mapped ob(ect it ma"es the method to become more
persistent. Oarba#e collection and termination of the *ava virtual machine stays as lon# as it is
deleted explicitly. It may head bac" to its transient state.
73 . !xplain about addClass function?
3his function translates a *ava class name into file name. 3his translated file name is then loaded as
an input stream from the *avaclass loader. 3his add.lass function is important if you +ant efficient
usa#e of classes in your code.
"prin/ GAQs
1. What is I%C 1or ,ependenc+ Injection2?
3he basic concept of the Inversion of .ontrol pattern !also "no+n as dependency in(ection$ is that you
do not create your ob(ects but describe ho+ they should be created. Cou don%t directly connect your
components and services to#ether in code but describe +hich services are needed by +hich
components in a confi#uration file. A container !in the case of the <prin# frame+or", the I'.
container$ is then responsible for hoo"in# it all up.
i.e., Applyin# Io., ob(ects are #iven their dependencies at creation time by some external entity that
coordinates each ob(ect in the system. 3hat is, dependencies are in(ected into ob(ects. <o, Io. means
an inversion of responsibility +ith re#ard to ho+ an ob(ect obtains references to collaboratin# ob(ects.
2. What are the different t+pes of I%C 1dependenc+ injection2 ?
3here are three types of dependency in(ection
Constructor Injection !e.#. /ico container, <prin# etc$ Dependencies are provided as
constructor parameters.
"etter Injection !e.#. <prin#$ Dependencies are assi#ned throu#h *ava?eans properties
!ex setter methods$.
Interface Injection !e.#. Avalon$ In(ection is done throu#h an interface.
Note: Spring supports only Constructor and Setter Injection
0. What are the benefits of I%C 1,ependenc+ Injection2?
?enefits of I'. !Dependency In(ection$ are as follo+s
5inimiFes the amount of code in your application. >ith I'. containers you do not care about
ho+ services are created and ho+ you #et references to the ones you need. Cou can also
easily add additional services by addin# a ne+ constructor or a setter method +ith little or no
extra confi#uration.
5a"e your application more testable by not re)uirin# any sin#letons or *9DI loo"up
mechanisms in your unit test cases. I'. containers ma"e unit testin# and s+itchin#
implementations very easy by manually allo+in# you to in(ect your o+n ob(ects into the ob(ect
under test.
Hoose couplin# is promoted +ith minimal effort and least intrusive mechanism. 3he factory
desi#n pattern is more intrusive because components or services need to be re)uested
explicitly +hereas in I'. the dependency is in(ected into re)uestin# piece of code. Also some
containers promote the desi#n to interfaces not to implementations desi#n concept by
encoura#in# mana#ed ob(ects to implement a +ell0defined service interface of your o+n.
I'. containers support ea#er instantiation and laFy loadin# of services. .ontainers also
provide support for instantiation of mana#ed ob(ects, cyclical dependencies, life cycles
mana#ement, and dependency resolution bet+een mana#ed ob(ects etc.
3. What is "prin/ ?
<prin# is an open source frame+or" created to address the complexity of
enterprise application development. 'ne of the chief advanta#es of the <prin# frame+or" is its layered
architecture, +hich allo+s you to be selective about +hich of its components you use +hile also
providin# a cohesive frame+or" for *2-- application development.
7. What are the advanta/es of "prin/ fra*ework?
3he advanta#es of <prin# are as follo+s
<prin# has layered architecture. 4se +hat you need and leave you don%t need no+.
<prin# -nables /'*' /ro#rammin#. 3here is no behind the scene ma#ic here. /'*'
pro#rammin# enables continuous inte#ration and testability.
Dependency In(ection and Inversion of .ontrol <implifies *D?.
'pen source and no vendor loc"0in.
9. What are features of "prin/ ?
#i/htwei/ht
sprin# is li#ht+ei#ht +hen it comes to siFe and transparency. 3he basic version of sprin# frame+or" is
around 15?. And the processin# overhead is also very ne#li#ible.
Inversion of control 1I%C2
Hoose couplin# is achieved in sprin# usin# the techni)ue Inversion of .ontrol. 3he ob(ects #ive their
dependencies instead of creatin# or loo"in# for dependent ob(ects.
Aspect oriented 1A%(2
<prin# supports Aspect oriented pro#rammin# and enables cohesive development by
separatin# application business lo#ic from system services.
Container
<prin# contains and mana#es the life cycle and confi#uration of application ob(ects.
)8C Gra*ework
<prin# comes +ith 5L. +eb application frame+or", built on core <prin# functionality. 3his frame+or"
is hi#hly confi#urable via strate#y interfaces, and accommodates multiple vie+ technolo#ies li"e *</,
Lelocity, 3iles, i3ext, and /'I. ?ut other frame+or"s can be easily used instead of <prin# 5L.
Brame+or".
Iransaction )ana/e*ent
<prin# frame+or" provides a #eneric abstraction layer for transaction mana#ement. 3his allo+in# the
developer to add the plu##able transaction mana#ers, and ma"in# it easy to demarcate transactions
+ithout dealin# +ith lo+0level issues. <prin#%s transaction support is not tied to *2-- environments
and it can be also used in container less environments.
6,-C !xception Candlin/
3he *D?. abstraction layer of the <prin# offers a meanin#ful exception hierarchy, +hich simplifies the
error handlin# strate#y. Inte#ration +ith 2ibernate, *D', and i?A3I< <prin# provides best Inte#ration
services +ith 2ibernate, *D' and i?A3I<
contexts for >eb0based applications. As a result, the <prin# frame+or" supports inte#ration +ith
*a"arta <truts. 3he >eb module also eases the tas"s of handlin# multi0part re)uests and bindin#
re)uest parameters to domain ob(ects.
; . What is web *odule?
3his module is built on the application context module, providin# a context that is appropriate for +eb0
based applications. 3his module also contains support for several +eb0oriented tas"s such as
transparently handlin# multipart re)uests for file uploads and pro#rammatic bindin# of re)uest
parameters to your business ob(ects. It also contains inte#ration support +ith Jakarta Struts.
<. What are the t+pes of ,ependenc+ Injection "prin/ supports?
"etter Injection
<etter0based DI is realiFed by callin# setter methods on your beans after invo"in# a no0ar#ument
constructor or no0ar#ument static factory method to instantiate your bean.
Constructor Injection
.onstructor0based DI is realiFed by invo"in# a constructor +ith a number of ar#uments, each
representin# a collaborator.
>. What is -ean Gactor+ ?
A ?eanBactory is li"e a factory class that contains a collection of beans. 3he ?eanBactory holds
?ean Definitions of multiple beans +ithin itself and then instantiates the bean +henever as"ed for by
clients.
?eanBactory is able to create associations bet+een collaboratin# ob(ects as they are
instantiated. 3his removes the burden of confi#uration from bean itself and the beans client.
?eanBactory also ta"es part in the life cycle of a bean, ma"in# calls to custom initialiFation and
destruction methods.
1@. What is Application Context?
A bean factory is fine to simple applications, but to ta"e advanta#e of the full po+er of the <prin#
frame+or", you may +ant to move up to <prin#s more advanced container, the application context.
'n the surface, an application context is same as a bean factory.?oth load bean definitions, +ire
beans to#ether, and dispense beans upon re)uest. ?ut it also provides
A means for resolvin# text messa#es, includin# support for internationaliFation.
A #eneric +ay to load file resources.
-vents to beans that are re#istered as listeners.
11. What is the difference between -ean Gactor+ and Application Context ?
'n the surface, an application context is same as a bean factory. ?ut application context offers much
more..
Application contexts provide a means for resolvin# text messa#es, includin# support for i1Nn
of those messa#es.
Application contexts provide a #eneric +ay to load file resources, such as ima#es.
Application contexts can publish events to beans that are re#istered as listeners.
.ertain operations on the container or beans in the container, +hich have to be handled in a
pro#rammatic fashion +ith a bean factory, can be handled declaratively in an application
context.
1esourceHoader support <prin#As 1esource interface us a flexible #eneric abstraction for
handlin# lo+0level resources. An application context itself is a 1esourceHoader, 2ence provides
an application +ith access to deployment0specific 1esource instances.
5essa#e<ource support 3he application context implements 5essa#e<ource, an interface
used to obtain localiFed messa#es, +ith the actual implementation bein# plu##able
12. What are the co**on i*ple*entations of the Application Context ?
3he three commonly used implementation of %Application .ontext% are
Class(athM*lApplicationContext It Hoads context definition from an ^5H file located in
the classpath, treatin# contextdefinitions as classpath resources. 3he application context is
loaded from the application%s classpath by usin# the code .
Application.ontext context T ne+ .lass/ath^mlApplication.ontext!=bean.xml=$:
Gile"+ste*M*lApplicationContext It loads context definition from an ^5H file in the
filesystem. 3he application context is loaded from the file system by usin# the code .
Application.ontext context T ne+ Bile<ystem^mlApplication.ontext!=bean.xml=$:
M*lWebApplicationContext It loads context definition from an ^5H file contained +ithin a
+eb application.
10. Cow is a t+pical sprin/ i*ple*entation look like ?
Bor a typical <prin# Application +e need the follo+in# files
An interface that defines the functions.
An Implementation that contains properties, its setter and #etter methods, functions etc.,
<prin# A'/ !Aspect 'riented /ro#rammin#$
A ^5H file called <prin# confi#uration file.
.lient pro#ram that uses the function.
13. What is the t+pical -ean life c+cle in "prin/ -ean Gactor+ Container ?
?ean life cycle in <prin# ?ean Bactory .ontainer is as follo+s
3he sprin# container finds the beanAs definition from the ^5H file and instantiates the bean.
4sin# the dependency in(ection, sprin# populates all of the properties as specified in the
bean definition
If the bean implements the ?ean9ameA+are interface, the factory calls set?ean9ame!$
passin# the beanAs ID.
If the bean implements the ?eanBactoryA+are interface, the factory calls set?eanBactory!$,
passin# an instance of itself.
If there are any ?ean/ost/rocessors associated +ith the bean, their post0
/rocess?eforeInitialiFation!$ methods +ill be called.
If an init0method is specified for the bean, it +ill be called.
Binally, if there are any ?ean/ost/rocessors associated +ith the bean, their
post/rocessAfterInitialiFation!$ methods +ill be called.
17. What do +ou *ean b+ -ean wirin/ ?
3he act of creatin# associations bet+een application components !beans$ +ithin the <prin# container
is reffered to as ?ean +irin#.
19. What do +ou *ean b+ Auto Wirin/?
3he <prin# container is able to auto+ire relationships bet+een collaboratin# beans. 3his means that
it is possible to automatically let <prin# resolve collaborators !other beans$ for your bean
by inspectin# the contents of the ?eanBactory. 3he auto+irin# functionality has five modes.
no
by9ame
by3ype
constructor
autodirect
1;. What is ,ele/atin/8ariable:esolver?
<prin# provides a custom *ava<erver Baces Lariable1esolver implementation that extends the
standard *ava <erver Bacesmana#ed beans mechanism +hich lets you use *<B and <prin# to#ether.
3his variable resolver is called asDelegatingVariale!esolver
1<. Cow to inte/rate 6ava "erver Gaces 16"G2 with "prin/?
*<B and <prin# do share some of the same features, most noticeably in the area of I'. services. ?y
declarin# *<B mana#ed0beans in the faces0confi#.xml confi#uration file, you allo+ the Baces<ervlet to
instantiate that bean at startup. Cour *<B pa#es have access to these beans and all of their
properties.>e can inte#rate *<B and <prin# in t+o +ays
,ele/atin/8ariable:esolver <prin# comes +ith a *<B variable resolver that lets you use
*<B and <prin# to#ether.
\Gxml versionT=1.J= encodin#T=43B0N=GM
\]D'.3C/- beans /4?HI. =077</1I9O77D3D ?-A977-9=
=http77+++.sprin#frame+or".or#7dtd7sprin#0beans.dtd=M
\faces0confi#M
\applicationM
\variable0resolverM
or#.sprin#frame+or".+eb.(sf.Dele#atin#Lariable1esolver
\7variable0resolverM
\7applicationM
\7faces0confi#M
3he Dele#atin#Lariable1esolver +ill first dele#ate value loo"ups to the default resolver of the
underlyin# *<B implementation, and then to <prin#%s %business context% >ebApplication.ontext. 3his
allo+s one to easily in(ect dependencies into one%s *<B0mana#ed beans.
Baces.ontext4tilscustom Lariable1esolver +or"s +ell +hen mappin# one%s properties to
beans in faces0confi#.xml, but at times one may need to #rab a bean explicitly. 3he
Baces.ontext4tils class ma"es this easy. It is similar to >ebApplication.ontext4tils, except
that it ta"es a Baces.ontext parameter rather than a <ervlet.ontext parameter.
Application.ontext ctx T
Baces.ontext4tils.#et>ebApplication.ontext!Baces.ontext.#et.urrentInstance!$$:
1>. What is 6ava "erver Gaces 16"G2 J "prin/ inte/ration *echanis*?
<prin# provides a custom *ava<erver Baces Lariable1esolver implementation that extends the
standard *ava<erver Baces mana#ed beans mechanism. >hen as"ed to resolve a variable name, the
follo+in# al#orithm is performed
Does a bean +ith the specified name already exist in some scope !re)uest, session,
application$G If so, return it
Is there a standard *ava<erver Baces mana#ed bean definition for this variable nameG If so,
invo"e it in the usual +ay, and return the bean that +as created.
Is there confi#uration information for this variable name in the <prin# >ebApplication.ontext
for this applicationG If so, use it to create and confi#ure an instance, and return that instance
to the caller.
If there is no mana#ed bean or <prin# definition for this variable name, return null instead.
?eanBactory also ta"es part in the life cycle of a bean, ma"in# calls to custom initialiFation and
destruction methods.
As a result of this al#orithm, you can transparently use either *ava<erver Baces or <prin# facilities to
create beans on demand.
2@. What is "i/nificance of 6"GJ "prin/ inte/ration ?
<prin# 0 *<B inte#ration is useful +hen an event handler +ishes to explicitly invo"e the bean factory to
create beans on demand, such as a bean that encapsulates the business lo#ic to be performed +hen a
submit button is pressed.
21. Cow to inte/rate +our "truts application with "prin/?
3o inte#rate your <truts application +ith <prin#, +e have t+o options
.onfi#ure <prin# to mana#e your Actions as beans, usin# the .ontextHoader/lu#in, and set
their dependencies in a <prin# context file.
<ubclass <prin#%s Action<upport classes and #rab your <prin#0mana#ed beans explicitly usin#
a #et>ebApplication.ontext!$ method.
22. What are %:)Xs "prin/ supports ?
"prin/ supports the followin/ %:)Xs
2ibernate
i?atis
*/A !*ava /ersistence A/I$
3opHin"
*D' !*ava Data 'b(ects$
'*?
20. What are the wa+s to access Cibernate usin/ "prin/ ?
3here are t+o approaches to <prin#As 2ibernate inte#ration
Inversion of .ontrol +ith a 2ibernate3emplate and .allbac"
-xtendin# 2ibernateDao<upport and Applyin# an A'/ Interceptor
23. Cow to inte/rate "prin/ and Cibernate usin/ Cibernate,ao"upport?
<prin# and 2ibernate can inte#rate usin# <prin#As <essionBactory called Hocal<essionBactory. 3he
inte#ration process is of 3 steps.
.onfi#ure the 2ibernate <essionBactory
-xtend your DA' Implementation from 2ibernateDao<upport
>ire in 3ransaction <upport +ith A'/
27. What are -ean scopes in "prin/ Gra*ework ?
3he <prin# Brame+or" supports exactly five scopes !of +hich three are available only if you are
usin# a +eb0a+are Application.ontext$. 3he scopes supported are listed belo+
<cope
Description
sin#leton <copes a sin#le bean definition to a sin#le ob(ect instance per <prin# Io. container.
prototype <copes a sin#le bean definition to any number of ob(ect instances.
re)uest <copes a sin#le bean definition to the lifecycle of a sin#le 233/ re)uest: that is each and
every 233/ re)uest +ill have its o+n instance of a bean created off the bac" of a sin#le
bean definition. 'nly valid in the context of a +eb0a+are <prin# Application.ontext.
session <copes a sin#le bean definition to the lifecycle of a 233/ <ession. 'nly valid in the
context of a +eb0a+are <prin# Application.ontext.
#lobal
session
<copes a sin#le bean definition to the lifecycle of a #lobal 233/ <ession. 3ypically only
valid +hen used in a portlet context. 'nly valid in the context of a +eb0a+are <prin#
Application.ontext.
29. What is A%(?
Aspect0oriented pro#rammin#, or A'/, is a pro#rammin# techni)ue that allo+s pro#rammers to
modulariFe crosscuttin# concerns, or behavior that cuts across the typical divisions of responsibility,
such as lo##in# and transaction mana#ement. 3he core construct of A'/ is the aspect, +hich
encapsulates behaviors affectin# multiple classes into reusable modules.
2;. Cow the A%( used in "prin/?
"#$ is used in the Spring %rame&ork:3o provide declarative enterprise services, especially as a
replacement for -*? declarative services. 3he most important such service is declarative transaction
mana#ement, +hich builds on the <prin# Brame+or"%s transaction abstraction.3o allo+ users to
implement custom aspects, complementin# their use of ''/ +ith A'/.
2<. What do +ou *ean b+ Aspect ?
A modulariFation of a concern that cuts across multiple ob(ects. 3ransaction mana#ement is a #ood
example of a crosscuttin# concern in *2-- applications. In <prin# A'/, aspects are implemented usin#
re#ular classes !the schema0based approach$ or re#ular classes annotated +ith the aAspect
annotation !aAspect* style$.
2>. What do +ou *ean b+ 6oint(oint?
A point durin# the execution of a pro#ram, such as the execution of a method or the handlin# of an
exception. In <prin# A'/, a (oin point al+ays represents a method execution.
0@. What do +ou *ean b+ Advice?
Action ta"en by an aspect at a particular (oin point. Different types of advice include =around,=
=before= and =after= advice. 5any A'/ frame+or"s, includin# <prin#, model an advice as an
interceptor, maintainin# a chain of interceptors =around= the (oin point.
01. What are the t+pes of Advice?
3ypes of advice
'efore advice Advice that executes before a (oin point, but +hich does not have the ability to
prevent execution flo+ proceedin# to the (oin point !unless it thro+s an exception$.
"fter returning advice Advice to be executed after a (oin point completes normally for
example, if a method returns +ithout thro+in# an exception.
"fter thro&ing advice Advice to be executed if a method exits by thro+in# an exception.
"fter (finally) advice Advice to be executed re#ardless of the means by +hich a (oin point
exits !normal or exceptional return$.
"round advice Advice that surrounds a (oin point such as a method invocation. 3his is the
most po+erful "ind of advice. Around advice can perform custom behavior before and after
the method invocation. It is also responsible for choosin# +hether to proceed to the (oin point
or to shortcut the advised method execution by returnin# its o+n return value or thro+in# an
exception
02. What are the t+pes of the transaction *ana/e*ent "prin/ supports ?
<prin# Brame+or" supports
/ro#rammatic transaction mana#ement.
Declarative transaction mana#ement.
00. What are the benefits of the "prin/ Gra*ework transaction *ana/e*ent ?
3he <prin# Brame+or" provides a consistent abstraction for transaction mana#ement that delivers
the follo+in# benefits
/rovides a consistent pro#rammin# model across different transaction A/Is such as *3A, *D?.,
2ibernate, */A, and *D'.
<upports declarative transaction mana#ement.
/rovides a simpler A/I for pro#rammatic transaction mana#ement than a number of complex
transaction A/Is such as *3A.
Inte#rates very +ell +ith <prin#%s various data access abstractions.
03. Wh+ *ost users of the "prin/ Gra*ework choose declarative transaction
*ana/e*ent ?
5ost users of the <prin# Brame+or" choose declarative transaction mana#ement because it is the
option +ith the least impact on application code, and hence is most consistent +ith the ideals of a
non0invasive li#ht+ei#ht container.
07. !xplain the si*ilarities and differences between !6- C)I and the "prin/ Gra*eworkEs
declarative transaction
*ana/e*ent ?
3he basic approach is similar it is possible to specify transaction behavior !or lac" of it$ do+n to
individual method level. It is
possible to ma"e a set1ollbac"'nly!$ call +ithin a transaction context if necessary. 3he differences
are
4nli"e -*? .53, +hich is tied to *3A, the <prin# Brame+or"%s declarative transaction
mana#ement +or"s in any environment. It can +or" +ith *D?., *D', 2ibernate or other
transactions under the covers, +ith confi#uration chan#es only.
3he <prin# Brame+or" enables declarative transaction mana#ement to be applied to any class,
not merely special classes such as -*?s.
3he <prin# Brame+or" offers declarative rollbac" rules this is a feature +ith no -*?
e)uivalent. ?oth pro#rammatic and declarative support for rollbac" rules is provided.
3he <prin# Brame+or" #ives you an opportunity to customiFe transactional behavior, usin#
A'/. >ith -*? .53, you have no +ay to influence the container%s transaction mana#ement
other than set1ollbac"'nly!$.
3he <prin# Brame+or" does not support propa#ation of transaction contexts across remote
calls, as do hi#h0end applicationservers.
09. What are objectBrelational *appin/ inte/ration *odule?
<prin# also supports for usin# of an ob(ect7relational mappin# !'15$ tool over strai#ht *D?. by
providin# the '15 module. <prin# provide support to tie into several popular #!* frame&orks,
includin# +iernate, JD#, and i'",IS S-. *aps. <prin#As transaction mana#ement supports each of
these #!* frame&orks as +ell as JD'C.
0;. When to use pro/ra**atic and declarative transaction *ana/e*ent ?
/ro#rammatic transaction mana#ement is usually a #ood idea only if you have a small number of
transactional operations.
'n the other hand, if your application has numerous transactional operations, declarative transaction
mana#ement is usually +orth+hile. It "eeps transaction mana#ement out of business lo#ic, and is not
difficult to confi#ure.
0<. !xplain about the "prin/ ,A% support ?
3he Data Access 'b(ect !DA'$ support in <prin# is aimed at ma"in# it easy to +or" +ith data access
technolo#ies li"e *D?., 2ibernate or *D' in a consistent +ay. 3his allo+s one to s+itch bet+een the
persistence technolo#ies fairly easily and it also allo+s one to code +ithout +orryin# about catchin#
exceptions that are specific to each technolo#y.
0>. What are the exceptions thrown b+ the "prin/ ,A% classes ?
<prin# DA' classes thro+ exceptions +hich are subclasses of
DataAccess-xception!or#.sprin#frame+or".dao.DataAccess-xception$.<prin# provides a convenient
translation from technolo#y0specific exceptions li"e <EH-xception to its o+n exception class hierarchy
+ith the DataAccess-xception as the root exception. 3hese exceptions +rap the ori#inal exception.
3@. What is "Q#!xceptionIranslator ?
<EH-xception3ranslator, is an interface to be implemented by classes that can translate bet+een
<EH-xceptions and <prin#%s o+n data0access0strate#y0a#nostic
or#.sprin#frame+or".dao.DataAccess-xception.
31. What is "prin/Es 6dbcIe*plate ?
<prin#%s Jdc,emplate is central class to interact +ith a database throu#h *D?.. *dbc3emplate
provides many convenience methods for doin# thin#s such as convertin# database data into primitives
or ob(ects, executin# prepared and callable statements, and providin# custom database error
handlin#.
*dbc3emplate template T ne+ *dbc3emplate!myData<ource$:
32. What is (repared"tate*entCreator ?
/repared<tatement.reator
Is one of the most common used interfaces for +ritin# data to database.
2as one method V create/repared<tatement!.onnection$
1esponsible for creatin# a /repared<tatement.
Does not need to handle <EH-xceptions.
30. What is "Q#(rovider ?
<EH/rovider
2as one method V #et<)l!$
3ypically implemented by /repared<tatement.reator implementers.
4seful for debu##in#.
33. What is :owCallbackCandler ?
3he 1o+.allbac"2andler interface extracts values from each ro+ of a 1esult<et.
2as one method V process1o+!1esult<et$
.alled for each ro+ in 1esult<et.
3ypically stateful.
37. What are the differences between !6- and "prin/ ?
<prin# and -*? feature comparison.
Beature
-*? <prin#
3ransaction
mana#ement
5ust use a *3A
transaction mana#er.
<upports transactions
that span remote method
calls.
<upports multiple transaction
environments throu#h its
/latform3ransaction5ana#er interface,
includin# *3A, 2ibernate, *D', and *D?..
Does not natively support distributed
transactionscit must be used +ith a *3A
transaction mana#er.
Declarative
transaction
support
.an define transactions
declaratively throu#h the
deployment descriptor.
.an define transaction
behavior per method or
per class by usin# the
.an define transactions declaratively
throu#h the <prin#confi#uration file or
throu#h class metadata.
.an define +hich methods to apply
transaction behavior explicitly or by usin#
+ildcard character 8.
.annot declaratively
define rollbac" behaviorc
this must be done
pro#rammatically.
re#ular expressions.
.an declaratively define rollbac" behavior
per method and per exception type.
/ersistence <upports pro#rammatic bean0
mana#ed persistence and
declarative container mana#ed
persistence.
/rovides a frame+or" for inte#ratin# +ith several
persistence technolo#ies, includin# *D?.,
2ibernate, *D', and i?A3I<.
Declarativesecurity
<upports declarative
security throu#h users
and roles. 3he
mana#ement and
implementation of users
and roles is container
specific.
Declarative security is
confi#ured in the
deployment descriptor.
9o security implementation out0of0the
box.
Ace#i, an open source security frame+or"
built on top of <prin#, provides
declarative security throu#h the
<prin#confi#uration file or class
metadata.
Distributed
computin#
/rovides container0mana#ed
remote method calls.
/rovides proxyin# for remote calls via 15I, *A^0
1/., and +eb services.
39 . ,o I need an+ other "%A( fra*ework to run "prin/ Web "ervices?
Cou don%t need any other <'A/ frame+or" to use <prin# >eb services, thou#h it can use
some of the features of Axis 1 and 2.
3; . I /et 'A)!"(AC!T!:: exceptions when usin/ "prin/JW". What can I do about it?
If you #et the follo+in# -xception
9A5-</A.-X-11 An attempt is made to create or chan#e an ob(ect in a +ay +hich is incorrect +ith
re#ard to namespaces.

5ost often, this exception is related to an older version of ^alan bein# used. 5a"e sure to up#rade to
2.&.J.
3< .,oes "prin/JW" run under 6ava 1.0?
<prin# >eb <ervices re)uires *ava 1.4 or hi#her.
3>. ,oes "prin/JW" work under 6ava 1.3?
<prin# >eb <ervices +or"s under *ava 1.4, but it re)uires some effort to ma"e it +or". *ava 1.4 is
bundled +ith the older ^5H parser .rimson, +hich does not handle namespaces correctly. Additionally,
it is bundled +ith an older version of ^alan, +hich also has problems. 4nfortunately, placin# ne+er
versions of these on the class path does not override them. .
3he only solution that +or"s is to add ne+er versions of ^erces and ^alan in the lib7endorsed directory
of your *DI, as explained in those BAEs !i.e.W*ALAX2'5-7lib7endorsed$. 3he follo+in# libraries are
"no+n to +or" +ith *ava 1.4.2
Hibrary
Lersion
^erces 2.N.1
^alan 2.&.J
^5H0A/Is 1.3.J4
<AA* 1.2
If you +ant to use ><0<ecurity, note that the ^+s<ecurityInterceptor re)uires *ava 5, because an
underlyin# library !^><<$ re)uires it. Instead, you can use the >ss4(<ecurityInterceptor.
7@ .,oes "prin/JW" work under 6ava 1.9?
*ava 1.6 ships +ith <AA* 1.3, *A^? 2.J, and *A^/ 1.4 !a custom version of ^erces and ^alan$.
'verridin# these libraries by puttin#different version on the classpath +ill result in various classloadin#
issues, or exceptions in or#.apache.xml.serialiFer.3o^5H<A^2andler. 3he only option for usin# more
recent versions is to put the ne+er version in the endorsed directory !see above$.
71 . Wh+ do the "prin/JW" unit tests fail under )ac %" M?
Bor some reason, Apple decided to include a *ava 1.4 compatibility (ar +ith their *DI 1.5. 3his (ar
includes the ^5H parsers +hich +ere included in *ava 1.4. 9o other *DI distribution does this, so it is
unclear +hat the purpose of this compatibility (ar is.
3he (ar can be found at
7<ystem7Hibrary7Brame+or"s7*avaL5.frame+or"7Lersions71.5.J7.lasses7.compatibility714compatibilit
y.(ar. Cou can safely remove or rename it, and the tests +ill run a#ain.
72 . What is "AA6?
<AA* is the <'A/ +ith Attachments A/I for *ava. Hi"e most *ava -- libraries, it consists of a set of
interfaces !saa(0api.(ar$, and implementations !saa(0impl.(ar$. >hen runnin# in a Application <erver,
the implementation is typically provided by the application server. /reviously, <AA* has been part of
*A^5, but it has been released as a seperate A/I as part of the , and also as part of*2-- 1.4. <AA* is
#enerally "no+n as the pac"a#e(avax.xml.soap.
<prin#0>< uses this standard <AA* library to create representations of <'A/ messa#es. Alternatively,
it can use
70 . What version of "AA6 does *+ application server support?
Application <erver
<AA* Lersion
?-A >ebHo#ic N 1.1
?-A >ebHo#ic K 1.171.28
?-A >ebHo#ic 1J 1.388
I?5 >eb<phere 6 1.2
<49 Olassfish 1 1.3
*?oss 4.2 1.3888
73 .I /et a 'o"uch)ethod!rror when usin/ "AA6. What can I do about it?
If you #et the follo+in# stac" trace
or#.sprin#frame+or".beans.factory.?ean.reation-xception -rror creatin# bean +ith name
%or#.sprin#frame+or".+s.soap.saa(.<aa(<oap5essa#eBactory% defined in <ervlet.ontext resource
R7>-?0I9B7sprin#+s0servlet.xmlS
Invocation of init method failed:
nested exception is (ava.lan#.9o<uch5ethod-rror
(avax.xml.soap.5essa#eBactory.ne+Instance!H(ava7lan#7<trin#:$H(avax7xml7soap75essa#eBactory:
.aused by
(ava.lan#.9o<uch5ethod-rror
(avax.xml.soap.5essa#eBactory.ne+Instance!H(ava7lan#7<trin#:$H(avax7xml7soap75essa#eBactory:

Hi"e most *2-- libraries, <AA* consists of t+o parts the A/I that consists of interfaces !saa(0api.(ar$
and the implementation !saa(0impl.(ar$. 3he stac" trace is due to the fact that you are usin# a ne+
version of the A/I !<AA* 1.3$, +hile your application server provides an earlier version of the
implementation !<AA* 1.2 or even 1.1$. <prin#0>< supports all three versions of <AA* !1.1 throu#h
1.3$, but thin#s brea" +hen it sees the 1.3 A/I, +hile there is no 1.3 implementation.
3he solution therefore is )uite simple to remove the ne+er 1.3 version of the A/I, from the class
path, and replace it +ith the version supported by your application server.
77 . I /et an &nsupported%peration!xception LIhis class does not support "AA6 1.1L when I
use "AA6 under Web#o/ic >. What can I do about it?
>ebHo#ic K has a "no+n bu# in the <AA* 1.2 implementation it implement all the 1.2 interfaces, but
thro+s 4nsupported'peration-xceptions +hen you call them. .onfusin#ly, the exception messa#e is
3his class does not support <AA* 1.1, even thou#h it supports <AA* 1.1 (ust fine: it (ust doesn%t
support <AA* 1.2. <ee alsot
<prin#0>< has a +or"around for this, +e basically use <AA* 1.1 only +hen dealin# +ith >ebHo#ic K.
4nfortunately, other frame+or"s +hich depend on <AA*, such as ^><<, do not have this +or"around.
3hese frame+or"s happily call <AA* 1.2 methods, +hich thro+ this exception.
3he solution is to not use ?-A%s version of <AA*, but to use another implementation, li"e the one from
Axis 1, or <49. In you application context, use the follo+in#
\bean idT=messa#eBactory= classT=or#.sprin#frame+or".+s.soap.saa(.<aa(<oap5essa#eBactory=M
\property nameT=messa#eBactory=M
\bean classT=com.sun.xml.messa#in#.saa(.soap.5essa#eBactoryImpl=7M
\7propertyM
\7beanM

79 . I /et an &nsupported%peration!xception LIhis class does not support "AA6 1.1L when I
use "AA6 under Web#o/ic 1@. What can I do about it?
>eblo#ic 1J ships +ith t+o <AA* implementations. ?y default the bu##y K.x implementation is used
!+hich lives in the pac"a#e +eblo#ic.+ebservice.core.soap$, but there is a ne+ implementation, +hich
supports <AA* 1.3 !+hich lives in the pac"a#e +eblo#ic.xml.saa($. ?y loo"in# at the D-?4O lo##in#
+hen <prin# >eb <ervices starts up, you can see +hich <AA* implementation is used.
3o use this ne+ version, you have to create a messa#e factory bean li"e so
\bean idT=messa#eBactory= classT=or#.sprin#frame+or".+s.soap.saa(.<aa(<oap5essa#eBactory=M
\property nameT=messa#eBactory=M
\bean classT=+eblo#ic.xml.saa(.5essa#eBactoryImpl=7M
\7propertyM
\7beanM

7; . I /et an Index%ut%f-ounds!xception when I use "AA6 under 6-oss. What can I do
about it?
3he <AA* implementation provided by *?oss has some issues. 3he solution is therefore not to use the
*?oss implementation, but to use another implementation. Bor instance, you can use <49%s reference
implementation li"e so
\bean idT=messa#eBactory= classT=or#.sprin#frame+or".+s.soap.saa(.<aa(<oap5essa#eBactory=M
\property nameT=messa#eBactory=M
\bean classT=com.sun.xml.messa#in#.saa(.soap.ver1X1.<'A/5essa#eBactory1X1Impl=7M
\7propertyM
\7beanM

7< . ,oes "prin/JW" run on I-) Web"phere?
>eb<phere bundles some libraries +hich are out0of0date, and need to be up#raded +ith more recent
versions. <pecifically, this includes ^5H0apis, ^erces, ^alan, and ><DH4*.
3here are a couple of +ays to up#rade these libraries, all usin# parent0last or application0first
classloadin#.
/ac"a#e the libraries as part of the >A1 !in >-?0I9B7lib$, and run the +eb application +ith
the parent0last !application0first$ classloadin#.
/ac"a#e the libraries as part of the -A1, add class0path entries to the manifest of the +eb
application, and run the entire application +ith the parent0last classloadin#.
.reate a ne+ classloader in the >eb<phere console, and associate the libraries +ith. <et this
classloader to parent0last.
3he last approach has the advanta#e of restrictin# the parent0last classloadin# to the conflictin#
libraries only, and not to the entire application.
7>. Wh+ does "prin/JW" onl+ support contractJfirst?
9ote that <prin#0>< only re)uires you to +rite the ^<D: the ><DH can be #enerated from that.
9@ . Cow do I retrieve the W",# fro* a "ervice?
3he Q><DH )uery parameter does not +or".
3he Q><DH )uery parameter is a +ay to #et a ><DH of a class. In <><, a service is #enerally not
implemented as a sin#le class, but as a collection of endpoints.
3here are t+o +ays to expose a ><DH
<imply add the ><DH to the root of the >A1, and the file is served normally. 3his has the
disadvanta#e that the =location= attribute in the ><DH is static, i.e. it does not necessarily
reflect the host name of the server. Cou can transform locations by usin# a
>sdlDefinition2andlerAdapter.
4se the5essa#eDispatcher<ervlet, +hich is done is the samples. -very >sdlDefinition listed
in the 80servlet.xml +ill be exposed under the bean name. <o if you define a >sdlDefinition
namedecho, it +ill be exposed as echo.+sdl !i.e.http77localhostNJNJ7echo7echo.+sdl$.
91 What is web *odule?
<prin# comes +ith a full0featured 5L. frame+or" for buildin# +eb applications. Althou#h <prin# can
easily be inte#rated +ith other 5L. frame+or"s, such as <truts, <prin#As 5L. frame+or" uses Io. to
provide for a clean separation of controller lo#ic frombusiness ob(ects. It also allo+s you to
declaratively bind re)uest parameters to your business ob(ects. It also can ta"e advanta#e of any of
<prin#As other services, such as I1N9 messa#in# and validation.
92 What is a -eanGactor+?
A ?eanBactory is an implementation of the factory pattern that applies Inversion of .ontrol to separate
the applicationAsconfi#uration and dependencies from the actual application code.
90 What is A%( Alliance?
A'/ Alliance is an open0source pro(ect +hose #oal is to promote adoption of A'/ and interoperability
amon# different A'/ implementations by definin# a common set of interfaces and components.
93 What is "prin/ confi/uration file?
<prin# confi#uration file is an ^5H file . 3his file contains the classes information and describes ho+
these classes are confi#ured and introduced to each other.
97 .What does a si*ple sprin/ application contain?
3hese applications are li"e any *ava application . 3hey are made up of several classes, each performin#
a specific purpose +ithin the application. ?ut these classes are confi#ured and introduced to each
other throu#h an ^5H file. 3his ^5H file describes ho+ to confi#ure the classes, "no+n as the<prin#
confi#uration file.
99 What is M)#-eanGactor+?
ean5actory has many implementations in <prin#. ?ut one of the most useful one
isor83s"rin8,ramewor:3beans3,actory3xml3>mlean5actory, +hich loads its beans based on the
definitions contained in an ^5H file. 3o create an >mlean5actory, pass a (ava.io.Input<tream to the
constructor. 3he 7n"ut)tream +ill provide the ^5H to the factory. Bor example, the
follo+in# code snippet uses a (ava.io.5ile7n"ut)tream to provide a bean definition ^5H file
to>mlean5actory.
-eanGactor+ factory T ne+ M*l-eanGactor+!ne+ GileInput"trea*!=beans.xml=$$:
3o retrieve the bean from a ?eanBactory, call the #et?ean!$ method by passin# the name of the bean
you +ant to retrieve.
5y?ean my?ean T !5y?ean$ factory./et-ean!=my?ean=$
9; . What are i*portant ApplicationContext i*ple*entations in sprin/ fra*ework?
Class(athM*lApplicationContext W 3his context loads a context definition from an ^5H file
located in the class path, treatin# context definition files as class path resources.
Gile"+ste*M*lApplicationContext W 3his context loads a context definition from an ^5H
file in the filesystem.
M*lWebApplicationContext W 3his context loads the context definitions from an ^5H file
contained +ithin a +eb application.
9< . !xplain -ean lifec+cle in "prin/ fra*ework?
3he sprin# container finds the beanAs definition from the ^5H file and instantiates the bean.
4sin# the dependency in(ection, sprin# populates all of the properties as specified in the bean
definition.
If the bean implements the -ean'a*eAware interface, the factory
calls set-ean'a*e12 passin# the beanAs ID.
If the bean implements the -eanGactor+Aware interface, the factory
calls set-eanGactor+12, passin# an instance of itself.
If there are any -ean(ost(rocessors associated +ith the bean, their postJ
(rocess-eforeInitiali=ation12 methods +ill be called.
If an init0method is specified for the bean, it +ill be called.
Binally, if there are any -ean(ost(rocessors associated +ith the bean,
their post(rocessAfterInitiali=ation12methods +ill be called.
9> What is bean wirin/?
.ombinin# to#ether beans +ithin the <prin# container is "no+n as bean +irin# or +irin#. >hen +irin#
beans, you should tell the container +hat beans are needed and ho+ the container should use
dependency in(ection to tie them to#ether.
;@ Cow do add a bean in sprin/ application?
\Gxml versionT=1.J= encodin#T=43B0N=GM
\]D'.3C/- beans /4?HI. =077</1I9O77D3D ?-A977-9=
=http77+++.sprin#frame+or".or#7dtd7sprin#0beans.dtd=M
\beansM
\bean idT=foo= classT=com.act.Boo=7M
Sbean idKLbarL classKLco*.act.-arLBH
\7beansM
;1. What are sin/leton beans and how can +ou create protot+pe beans?
?eans defined in sprin# frame+or" are sin#leton beans. 3here is an attribute in bean ta# named
bsin#letonA if specified true then bean becomes sin#leton and if set to false then the bean becomes a
prototype bean. ?y default it is set to true. <o, all the beans in sprin# frame+or" are by default
sin#leton beans.
\beansM
\bean idT=bar= classT=com.act.Boo= sin#letonT[false[7M
\7beansM
;2 . What are the i*portant beans lifec+cle *ethods?
3here are t+o important bean lifecycle methods. 3he first one is setup +hich is called +hen the bean
is loaded in to the container. 3he second method is the teardo+n method +hich is called +hen the
bean is unloaded from the container.
;0 . Cow can +ou override beans default lifec+cle *ethods?
3he bean ta# has t+o more important attributes +ith +hich you can define your o+n custom
initialiFation and destroy methods. 2ere I have sho+n a small demonstration. 3+o ne+ methods
foo<etup and foo3eardo+n are to be added to your Boo class.
\beansM
\bean idT=bar= classT=com.act.Boo= init0methodT[foo<etup[ destroyT[foo3eardo+n[7M
\7beansM
;3 . What are Inner -eans?
>hen +irin# beans, if a bean element is embedded to a property ta# directly, then that bean is said to
the Inner ?ean. 3he dra+bac" of this bean is that it cannot be reused any+here else.
;7. What are the different t+pes of bean injections?
3here are t+o types of bean in(ections.
?y setter
?y constructor
;9. What is Auto wirin/?
Cou can +ire the beans as you +ish. ?ut sprin# frame+or" also does this +or" for you. It can auto
+ire the related beans to#ether. All you have to do is (ust set the auto+ire attribute of bean ta# to an
auto+ire type.
\beansM
\bean idT=bar= classT=com.act.Boo= Auto+ireT[auto+ire type[7M
\7beansM
;; . What are different t+pes of Autowire t+pes?
3here are four different types by +hich auto+irin# can be done.
o by9ame
o by3ype
o constructor
o autodetect
;<. What are the different t+pes of events related to #isteners?
3here are a lot of events related to Application.ontext of sprin# frame+or". All the events are
subclasses of or#.sprin#frame+or".context.Application0-vent. 3hey are
.ontext.losed-vent V 3his is fired +hen the context is closed.
.ontext1efreshed-vent V 3his is fired +hen the context is initialiFed or refreshed.
1e)uest2andled-vent V 3his is fired +hen the +eb context handles any re)uest.
;>. What is an Aspect?
An aspect is the cross0cuttin# functionality that you are implementin#. It is the aspect of your
application you are modulariFin#. An example of an aspect is lo##in#. Ho##in# is somethin# that is
re)uired throu#hout an application. 2o+ever, because applications tend to be bro"en do+n into layers
based on functionality, reusin# a lo##in# module throu#h inheritance does not ma"e sense. 2o+ever,
you can create a lo##in# aspect and apply it throu#hout your application usin# A'/.
<@ . What is a 6ointpoint?
A (oinpoint is a point in the execution of the application +here an aspect can be plu##ed in. 3his point
could be a method bein# called, an exception bein# thro+n, or even a field bein# modified. 3hese are
the points +here your aspectAs code can be inserted into the normal flo+ of your application to add
ne+ behavior.
<1 What is an Advice?
Advice is the implementation of an aspect. It is somethin# li"e tellin# your application of a ne+
behavior. Oenerally, and advice isinserted into an application at (oinpoints.
<2 What is a (ointcut?
A pointcut is somethin# that defines at +hat (oinpoints an advice should be applied. Advices can be
applied at any (oinpoint that is supported by the A'/ frame+or". 3hese /ointcuts allo+ you to specify
+here theadvice can be applied.
<0 What is an Introduction in A%(?
An introduction allo+s the user to add ne+ methods or attributes to an existin# class. 3his can then be
introduced to an existin# class +ithout havin# to chan#e the structure of the class, but #ive them the
ne+ behavior and state.
<3 What is a Iar/et?
A tar#et is the class that is bein# advised. 3he class can be a third party class or your o+n class to
+hich you +ant to add your o+n custom behavior. ?y usin# the concepts of A'/, the tar#et class is
free to center on its ma(or concern, una+are to any advice that is bein# applied.
<7 . What is a (rox+?
A proxy is an ob(ect that is created after applyin# advice to a tar#et ob(ect. >hen you thin" of client
ob(ects the tar#et ob(ect and the proxy ob(ect are the same.
<9 .What is *eant b+ Weavin/?
3he process of applyin# aspects to a tar#et ob(ect to create a ne+ proxy ob(ect is called as >eavin#.
3he aspects are +oven intothe tar#et ob(ect at the specified (oinpoints.
<; What are the different points where weavin/ can be applied?
.ompile 3ime
.lassload 3ime
1untime
<< . What are the different advice t+pes in sprin/?
Around Intercepts the calls to the tar#et method
?efore 3his is called before the tar#et method is invo"ed
After 3his is called after the tar#et method is returned
3hro+s 3his is called +hen the tar#et method thro+s and exception
Around or#.aopalliance.intercept.5ethodInterceptor
?efore or#.sprin#frame+or".aop.?eforeAdvice
After or#.sprin#frame+or".aop.After1eturnin#Advice
3hro+s or#.sprin#frame+or".aop.3hro+sAdvice
<> What are the different t+pes of Auto(rox+in/?
?ean9ameAuto/roxy.reator
DefaultAdvisorAuto/roxy.reator
5etadata autoproxyin#
>@ What kind of exceptions those sprin/ ,A% classes throw?
3he sprin#fghs DA' class does not thro+ any technolo#y related exceptions such as
<EH-xception. 3hey thro+ exceptions +hich are subclasses of DataAccess-xception.
>1 What is ,ataAccess!xception?
DataAccess-xception is a 1untime-xception. 3his is an 4nchec"ed -xception. 3he user is not
forced to handle these "inds of exceptions.
>2 Cow can +ou confi/ure a bean to /et ,ata"ource fro* 6',I?
\bean idT=data<ource= classT=or#.sprin#frame+or".(ndi.*ndi'b(ectBactory?ean=M
\property nameT=(ndi9ame=M
\valueM(avacomp7env7(dbc7myDatasource\7valueM
\7propertyM
\7beanM
>0 Cow can +ou create a ,ata"ource connection pool?
\bean idT=data<ource= classT=or#.apache.commons.dbcp.?asicData<ource=M
\property nameT=driver=M
\valueMW6db.driver;\7valueM
\7propertyM
\property nameT=url=M
\valueMW6db.url;\7valueM
\7propertyM
\property nameT=username=M
\valueMW6db.username;\7valueM
\7propertyM
\property nameT=pass+ord=M
\valueMW6db.pass+ord;\7valueM
\7propertyM
\7beanM
>3 Cow 6,-C can be used *ore efficientl+ in sprin/ fra*ework?
*D?. can be used more efficiently +ith the help of a template class provided by sprin#
frame+or" called as *dbc3emplate.
>7 Cow 6dbcIe*plate can be used?
>ith use of <prin# *D?. frame+or" the burden of resource mana#ement and error handlin# is
reduced a lot. <o it leaves developers to +rite the statements and )ueries to #et the data to
and from the database.
*dbc3emplate template T ne+ *dbc3emplate!myData<ource$:
A simple DA' class loo"s li"e this.
public class <tudentDao*dbc implements <tudentDao 6
private *dbc3emplate (dbc3emplate:
public void set*dbc3emplate!*dbc3emplate (dbc3emplate$ 6
this.(dbc3emplate T (dbc3emplate:
;
more..
;
3he confi#uration is sho+n belo+.
\bean idT=(dbc3emplate= classT=or#.sprin#frame+or".(dbc.core.*dbc3emplate=M
\property nameT=data<ource=M
\ref beanT=data<ource=7M
\7propertyM
\7beanM
\bean idT=studentDao= classT=<tudentDao*dbc=M
\property nameT=(dbc3emplate=M
\ref beanT=(dbc3emplate=7M
\7propertyM
\7beanM
\bean idT=courseDao= classT=.ourseDao*dbc=M
\property nameT=(dbc3emplate=M
\ref beanT=(dbc3emplate=7M
\7propertyM
\7beanM
>9 Cow do +ou write data to backend in sprin/ usin/ 6dbcIe*plate?
3he *dbc3emplate uses several of these callbac"s +hen +ritin# data to the database. 3he
usefulness you +ill find in each of these interfaces +ill vary. 3here are t+o simple interfaces.
'ne is /repared<tatement.reator and the other interface is ?atch/repared<tatement<etter.
>; !xplain about (repared"tate*entCreator?
/repared<tatement.reator is one of the most common used interfaces for +ritin# data to
database. 3he interface has one method create/repared<tatement!$.
/repared<tatement create/repared<tatement!.onnection conn$
thro+s <EH-xception:
>hen this interface is implemented, +e should create and return a /repared<tatement from
the .onnection ar#ument, and the exception handlin# is automatically ta"en care off. >hen
this interface is implemented, another interface <)l/rovider is also implemented +hich has a
method called #et<)l!$ +hich is used to provide s)l strin#s to *dbc3emplate.
>< !xplain about -atch(repared"tate*ent"etter?
If the user +hat to update more than one ro+ at a shot then he can #o for
?atch/repared<tatement<etter. 3his interface provides t+o methods
setLalues!/repared<tatement ps, int i$ thro+s <EH-xception:

int #et?atch<iFe!$:
3he #et?atch<iFe!$ tells the *dbc3emplate class ho+ many statements to create. And this also
determines ho+ many times setLalues!$ +ill be called.
>>. !xplain about :owCallbackCandler and wh+ it is used?
In order to navi#ate throu#h the records +e #enerally #o for 1esult<et. ?ut sprin# provides an
interface that handles this entire burden and leaves the user to decide +hat to do +ith each
ro+. 3he interface provided by sprin# is 1o+.allbac"2andler. 3here is a method process1o+!$
+hich needs to be implemented so that it is applicable for each and everyro+.
void process1o+!(ava.s)l.1esult<et rs$:

1@@ What is 6,-C abstraction and ,A% *odule?
4sin# this module +e can "eep up the database code clean and simple, and prevent problems
that result from a failure to close database resources. A ne+ layer of meanin#ful exceptions on
top of the error messa#es #iven by several database servers is bou#ht in this module. In
addition, this module uses <prin#As A'/ module to provide transaction mana#ement services
for ob(ects in a <prin# application.

Inner class
1. What is inner class and when we should /o for inner classes?

<ome times +e can declare a class inside another class such type of classes are called inner classes
!xa*ple
.lass .ar6
77more code here
.lass -n#ine6
77more code here
;
;
>ithout existin# .ar ob(ect there is no chance of existin# -n#ine ob(ect, hence -n#ine class has
declared inside .ar class.

2.Cow *an+ t+pes of inner classes are present?
3here are four types of inner classes are present
o 9ormal or re#ular inner class
o 5ethod local inner class
o Anonymous inner class
o <tatic nested class
0.What is *ethod local inner class?
<ometimes +e can declare a class inside a method such type of classes are called method
local
inner classes
3he main purpose of method local inner classes is to define method specific functionality
3he scope of method local inner classes is the scope of the method +here it is declared.
3his is the mostly rarely used type of inner classes.
!xa*ple
class 3est6
public void m1!$6
class Inner 6
public void sum!int I,int ($6
<ystem.out.println!i@*$:
;77sum
;77inner
Inner iTne+ Inner!$:
i.sum!1J,2J$:
77more code here
I.sum!1JJ,3J3$:
77more code here
i.sum!1J2,N4$:
;77m1!$
/ublic static void main!$6
9e+ 3est!$.m1!$:
;
;

3.What is anon+*ous inner class?
<ome times +e can declare a inner class +ithout name such type of inner classes are called
anonymous inner classes
Anonymous inner classes can be divided into 3 cate#ories
Anonymous inner class that extends a class
Anonymous inner class that implements an interface
Anonymous inner class that defines inside a method ar#ument
A'%'Y)%&" I''!: C#A"" ICAI !MI!'," A C#A""
!xa*ple
.lass popcorn6
/ublic void taste!$6
<ystem.out.println!Zit is salty[$:
;
77more code here
;
.lass 3est6
/ublic static void main!<trin#RS ar#s$
6
/opcorn pTne+ /opcorn!$
6 77 here +e are creatin# child class for popcorn
/ublic void taste!$6
<ystem.out.println!Zit is s+eet[$:
;
;:77here semicolon indicates +e r creatin# child class ob(ect +ith
parent
77 class reference here child class dosent contain name
p.taste!$77 it is s+eet
/opcorn pTne+ /opcorn!$:
p1.taste!$ 77it is salty
;
;


A'%'Y)%&" I''!: C#A"" ICAI I)(#!)!'I" A' I'I!:GAC!
exa*ple
class 3est6
/ublic static void main!<trin#RS ar#s$6
1unnable rTne+ 1unnable!$6
/ublic void run!$6
for!int iTJ:i\1J:i@@$6
<ystem.out.printin!Zchild thread[$:
;
;
;:
3hread tTne+ 3hread!r$:
t.start!$:
for!int iTJ:i\1J:i@@$6
<ystem.out.printin!Zmain thread[$:
;
;
;
DonAt become fool that here +e are creatin# ob(ect of interface 1unnable.2ere +e are actually
creatin# an ob(ect of class that is implemented 1unnable interface.
A'%'Y)%&" I''!: C#A"" ICAI ,!GI'!" I'"I,! A )!IC%, A:?&)!'I
!xa*ple
.lass 3est6
/ublic static void main!<trin#RS ar#s$6
9e+ 3hread!ne+ 1unnable!$
6
/ublic void run!$6
for!int iTJ:i\1J:i@@$6
<ystem.out.printin!Zchild thread[$:
;
;
;$.start!$:
for!int iTJ:i\1J:i@@$6
<ystem.out.printin!Zmain thread[$:
;
;77main
;773est


7. With out havin/ na*e of class how we can create an object and utili=e the functionalit+
of Anon+*ous inner class?
?y usin# parent class names
9. What is difference between anon+*ous inner class and /eneral class?
A #eneral class can extend only one class at a time of course inner class can extend only one
class at a 3ime.
A #eneral class can implement any no of interfaces at a time but a anonymous inner class can
implement only one interface at a time
A #eneral class can extend a class and can implement an interface simultaneously but an
anonymous inner class can extend a class or can implement an interface one at a time but not
both simualtaneously

;. What is difference between nor*al inner class and static nested class?

'or*al Inner Class "tatic 'ested Class
1. Inner class ob(ect al+ays associated +ith
outer class ob(ect ie +ithout existin# outer
class ob(ect there is no chance of existin#
inner class ob(ect.
1. 9ested class ob(ect never associated +ith
outer class ob(ect , ie +ithout existin# outer
class ob(ect inner class ob(ect can exist
2. Inside normal inner class +e cant declare
static members.
3. Inside static nested class can
declare static members
4. >e cant place main method in normal inner
class and hence innocation of inner class
directly from command prompt is not
possible.
2. >e can place main method in static nested
class and hence innocation of nested
class directly from command prompt is
possible
5. Brom normal inner class +e can access both
static and non static members of outer class.
3. Brom static nested class +e can access
only static member of outer class
<.What is static nested calss?wh+ the ter* nested instead of inner in static nested class?
<ome times +e can declare inner class +ith static modifier such type of inner class are called
static
nested classes.the term nested instead of static because +ithout existin# outer class ob(ect inner
class ob(ect can exist.
!xa*ple
.lass outer6
<tatic class 9ested6
/ublic static void main!<trin#RS ar#s$6
<ystem.out.println!Znested class main!$[$:
;
;
/ublic static void main!<trin#RS ar#s$6
<ystem.out.println!Zouter class main!$[$:
;
;
*ava 'uter
'7/
'uter class main!$
*ava 'uterW9ested
'7/
9ested class main!$


>. Inside inner class is it possible to declare *ain12?
9o it is not possible to declare main !$ inside inner class but in static nested class it is possible
for
-xample refer above code
Weblo/ic Application "erver GAQs
1.What is application server?
An application server is a soft+are frame+or" dedicated to the efficient execution of
procedures !scripts, routines, pro#rams ...$ for supportin# the construction of applications. 3he
term +as created in the context of +eb applications. In these, the application server acts as a
set of components accessible to the soft+are developer throu#h an A/I defined by the platform
itself. 3hese components are usually performed in the same machine +here the +eb server is
runnin#, and their main (ob is to support the construction of dynamic pa#es.
'ther uses of the term can refer to
o the services that a server ma"es available
o the computer hard+are on +hich the services run
6ava application servers
Bollo+in# the success of the *ava platform, the term application server sometimes refers to a
*2-- or *ava -- 5 applicationserver. <ome of the better0"no+n *ava -nterprise
-dition application servers include
o Apache 3omcat !Apache <oft+are Boundation$
o 3cat <erver !5ule<oft$
o >eb<phere Application <erver and >eb<phere Application <erver .ommunity -dition
!I?5$
o <ybase -nterprise Application <erver !<ybase Inc$
o >ebHo#ic <erver !'racle$
o *?oss !1ed 2at$
o Apache Oeronimo !Apache <oft+are Boundation$
o 'racle '.4* !'racle$
o <A/ 9et+eaver A< !A?A/7*ava$ !<A/$
o >eb'b(ects !Apple Inc.$
3he +eb modules include servlets and *ava<erver /a#es. ?usiness lo#ic resides in -nterprise
*ava?eans !-*?03 and later$. 3he 2ibernate pro(ect offers an -*?03 container implementation
for the *?oss application server. 3omcat from Apache and *'nA< from 'b(ect>eb exemplify
typical containers +hich can store these modules.
A *ava <erver /a#e !*</$ !a servlet from *ava$ executes in a +eb container c the *ava
e)uivalent of .OI scripts. *</s provide a +ay to create 235H pa#es by embeddin# references
to the server lo#ic +ithin the pa#e. 235H coders and *ava pro#rammers can +or" side by side
by referencin# each other%s code from +ithin their o+n. *ava?eans are the independent class
components of the *ava architecture from <un 5icrosystems.
2.What is web server?
3he primary function of a +eb server is to deliver +eb pa#es !235H documents$ and associated
content !e.#. ima#es, style sheets, *ava<cript%s$ to clients. A client, commonly a +eb bro+ser
or +eb cra+ler, ma"es a re)uest for a specific resource usin# 233/ and, if all #oes +ell, the
server responds +ith the content of that resource. 3he resource is typically a real file on the
server%s secondary memory, but this is not necessarily the case and depends on ho+ the +eb
server is implemented.
>hile the primary function is to serve content, a full implementation of 233/ also includes a
+ay of receivin# content from clients. 3his feature is used for submittin# +eb forms, includin#
uploadin# of files.
5any #eneric +eb servers also support server0side scriptin# !e.#. Apache 233/ <erver and
/2/$. 3his means that the behavior of the +eb server can be scripted in separate files, +hile
the actual server soft+are remains unchan#ed. 4sually, this functionality is used to create
235H documents on0the0fly as opposed to return fixed documents. 3his is referred to as
dynamic and static content respectively.
Cistor+ of web servers
In 1KNK 3im ?erners0Hee proposed to his employer .-19 !-uropean 'r#aniFation for 9uclear
1esearch$ a ne+ pro(ect, +hich had the #oal of easin# the exchan#e of information bet+een
scientists by usin# a hypertext system. As a result of the implementation of this pro(ect, in
1KKJ ?erners0Hee +rote t+o pro#rams
o a bro+ser called >orld+ide >eb:
o the +orld%s first +eb server, later "no+n as .-19 httpd, +hich ran on 9e^3<3-/.
?et+een 1KK1 and 1KK4 the simplicity and effectiveness of early technolo#ies used to surf and
exchan#e data throu#h the >orld >ide >eb helped to port them to many different operatin#
systems and spread their use amon# lots of different social #roups of people, first in scientific
or#aniFations, then in universities and finally in industry.
In 1KK4 3im ?erners0Hee decided to constitute the >orld >ide >eb .onsortium to re#ulate the
further development of the many technolo#ies involved !233/, 235H, etc.$ throu#h a
standardiFation process.
Co**on features
o Lirtual hostin# to serve many +eb sites usin# one I/ address.
o Har#e file support to be able to serve files +hose siFe is #reater than 2 O? on 32 bit
'<.
o ?and+idth throttlin# to limit the speed of responses in order to not saturate the
net+or" and to be able to serve more clients.
0.What is the difference between Web server and Application "erver?
Application "erver
>ebserver serves pa#es for vie+in# in +eb bro+ser, application server provides
exposes business lo#ic for clientapplications throu#h various protocols
>ebserver exclusively handles http re)uests. Application server serves business lo#ic
to application pro#rams throu#h any number of protocols.
>ebserver dele#ation model is fairly simple, +hen the re)uest comes into the +ebserver, it
simply passes the re)uest to the pro#ram best able to handle it!<erver side pro#ram$. It may
not support transactions and database connection poolin#.
Application server is more capable of dynamic behavior than +ebserver. >e can also
confi#ure application server to +or" as a +ebserver. <imply application server is a superset of
+ebserver.
W!- "erver
>eb <erver serves static 235H pa#es or #ifs, (pe#s, etc., and can also run code +ritten in .OI,
*</ etc. A >eb server handles the 233/ protocol. -# of some +eb server are II< or apache.
An Application <erver is used to run business lo#ic or dynamically #enerated presentation code.
It can either be .9-3 based or *2-- based !?-A >ebHo#ic <erver, I?5 >eb<phere, *?oss$.
A *2-- application server runs servlets and *</s !infact a part of the app server called +eb
container is responsible for runnin# servlets and *</s$ that are used to create 235H pa#es
dynamically. In addition, *2-- application server can run -*?s 0 +hich are used to
execute business lo#ic.
An Application server has a %built0in% +eb server: in addition to that it supports other modules
or features li"e e0businessinte#ration, independent mana#ement and security module, portlets
etc.
3.What is the ,o*ain in Weblo/ic serve?
o Domain is a lo#ically related #roup of 'racle >ebHo#ic <erver resources that are
mana#ed as a sin#le unit
o Domain /rovides one point of administration
o .an lo#ically separate
Development, test, and production applications
'r#aniFational divisions
7.What are the ,o*ain :estrictions?
o -ach domain re)uires its o+n Administration <erver.
o A cluster cannot span multiple domains.
o 3he 5ana#ed <ervers in a domain must run the same version of 'racle >ebHo#ic
<erver.
o 3he Administration <erver in a domain must run the same or hi#her version as
5ana#ed <ervers in the domain.
9.What is the server?
o A server is an instance of +eblo#ic.<erver executin# in a *ava Lirtual 5achine !*L5$.
o A server
1uns on a desi#nated 'racle >ebHo#ic <erver machine
2as a dedicated amount of 1A5
Is multithreaded
o 3+o types of servers
Administration <erver
5ana#ed <erver
;.What is the Ad*inistration server?
Administration server is central point of control for a domain. It stores the confi#uration information
and lo#s for a domain. And it runs the >eblo#ic Administration console.
<.What is the )ana/ed "erver?
5ana#ed server is a server in a domain that is not the Administration server. It contacts the
administration server for confi#uration information. It runs business application in a production
environment. It is independent of all other 5ana#ed servers in a domain !unless they are not in
a cluster$. Cou can have many mana#ed servers in a domain. Individual mana#ed servers are typically
added for capacity and application isolation.
>.Cow Ad*inistration server and )ana/ed servers will interact?
o 3he Administration <erver stores the master copy of the domain confi#uration,
includin# the confi#uration for all 5ana#ed <ervers in the domain.
o -ach 5ana#ed <erver stores a local copy of the domain confi#uration file.
o >hen a 5ana#ed <erver starts, it connects to the Administration <erver to synchroniFe
the confi#uration.
o >hen the confi#uration is chan#ed, the Administration <erver sends the chan#ed
confi#uration to the 5ana#ed <ervers.
1@.What is a )achine in %racle Weblo/ic "erver?
A 5achine in a 'racle >eblo#ic server is a computer that hosts the 'racle >eblo#ic <erver instances.
1uns a supported operatin# system platform and it is used by 9ode 5ana#er to restart a failed
5ana#ed servers.
11.What is a Cluster in %racle Weblo/ic server?
A cluster is a Ho#ical #roup of >eblo#ic servers. 'racle >eblo#ic server provides 2IO2 ALAIHA?IHI3C
Q H'AD ?AHA9.I9O +ith help of cluster.
12.What is a 'ode )ana/er?
A 9ode 5ana#er is a utility or process runnin# on a physical server that enables startin#, stoppin#,
suspendin# or restartin# the Administration and 5ana#ed servers remotely. It is not associated +ith
a Domain. R9ode mana#er can start any server instances that are resides on the
same physical serverS.
10.Cow *an+ wa+s we can install %racle Weblo/ic "erver?
Cou can install 'racle >eblo#ic server in three different +ays.
O4I mode !extract server1J3Xlinux32.bin7double clic" on server1J3X+in32.exe $
.onsole mode !ciMserver1J3Xlinux32.bin VmodeTconsole Vlo#Tciconsoleinstal.lo#$
<ilent mode !ciM server1J3Xlinux32.bin VmodeTsilent VsilentXxmlTpathXtoXsilent.xml V
lo#Tcisilentinstal.lo#$
13.What is the default database for Weblo/ic server?
/oint base is the default database. 3his database comes alon# +ith >eblo#ic soft+are bundle.
17.Cow *an+ wa+s we can confi/ure a do*ain?
Cou can confi#ure 'racle >eblo#ic server domains in t+o +ays.
Oraphical 5ode !confi#.cmd R<cripts are in the \>HX2'5-M7common7bin directoryS$
.onsole 5ode !confi#.cmd VmodeTconsole$
19.Cow *an+ wa+s +ou can start Ad*inistration server?
Cou can start the Administration server usin# 5 +ays.
o +eblo#ic.<erver !only in development$
o <tart menu !only >indo+s$
o D'5AI9XDI17bin7start>ebHo#ic.sh
o >ebHo#ic <criptin# 3ool !>H<3$ and 9ode 5ana#er
o >H<3 +ithout 9ode 5ana#er
1;.Cow *an+ wa+s +ou can confi/ure *ana/ed servers?
Cou can confi#ure the 5ana#ed server usin# 3 +as.
o Domain .onfi#uration >iFard
o Administration .onsole
o .ommand Hine !>H<3$
1<.Cow *an+ wa+s +ou can confi/ure a *achines?
Cou can confi#ure machines by usin# follo+in#
o Domain .onfi#uration >iFard
o Administration .onsole
o .ommand Hine !>H<3$
1>.Cow *an+ wa+s +ou can start *ana/ed servers?
<tart 5ana#ed <ervers by usin#
o +eblo#ic.<erver
o D'5AI9XDI17bin7start5ana#ed>ebHo#ic.sh
o Administration .onsole
o >H<3 and 9ode 5ana#er
2@.Cow do I provide user credentials for startin/ a server?
>hen you create a domain, the .onfi#uration >iFard prompts you to provide the username and
pass+ord for an initial administrative user. If you create the domain in development mode, the +iFard
saves the username and encrypted pass+ord in a boot identity file. A >ebHo#ic <erver instance can
refer to a boot identity file durin# its startup process. If a server instance does not find such a file, it
prompts you to enter credentials.
If you create a domain in production mode, or if you +ant to chan#e user credentials in an existin#
boot identity file, you can create a ne+ boot identity file. >ebHo#ic <erver does not support copyin# a
boot identity file from one server root directory to another. Bor information on creatin# and usin# boot
identity files, see ?oot Identity Biles in Administration .onsole 'nline 2elp.
21.Can I start a )ana/ed "erver if the Ad*inistration "erver is unavailable?
?y default, if a 5ana#ed <erver is unable to connect to the specified Administration <erver
durin# startup, it can retrieve its confi#uration by readin# a confi#uration file and other files directly.
Cou cannot chan#e the server%s confi#uration until the Administration <erver is available. A 5ana#ed
<erver that starts in this +ay is runnin# in 5ana#ed <erver Independence mode. Bor more
information, see <tartin# a 5ana#ed <erver >hen the Administration <erver Is 9ot Accessible in
.onfi#urin# and 5ana#in# >ebHo#ic <erver.
22.What is the function of I0 in Web#o/ic "erver?
33 provides a frame+or" for >ebHo#ic <erver messa#es that support for enhancements. 3hese
enhancements include abbreviations and features, such as ob(ect replacement, that +or" in the
context of >ebHo#ic <erver clusters and 233/ and other product tunnelin#. 33 predates *ava 'b(ect
<erialiFation and 15I, +hile closely trac"in# and levera#in# these specifications. 33 is a superset of
*ava 'b(ect. <erialiFation or 15I: anythin# you can do in *ava 'b(ect <erialiFation and 15I can be
done over 33. 33 is mandated bet+een >ebHo#ic <ervers and bet+een pro#rammatic clients and a
>ebHo#ic <erver cluster. 233/ and II'/ are optional protocols that can be used to communicate
bet+een other processes and >ebHo#ic <erver. It depends on +hat you +ant to do. Bor example
+hen you +ant to communicate bet+een a bro+ser and >ebHo#ic <erver 00 use 233/, or an '1? and
>ebHo#ic <erver0II'/.
20.What is the easiest wa+ to set the classpath?
>ebHo#ic <erver installs the follo+in# script that you can use to set the classpath that a server
re)uires
>HX2'5-iserveribiniset>H<-nv.cmd !on >indo+s$
>HX2'5-7server7bin7set>H<-nv.sh !on 49I^$
>here >HX2'5- is the directory in +hich you installed >ebHo#ic <erver. Bor more information, see
=<ettin# the .lasspath= in the >ebHo#ic <erver .ommand 1eference.
23.Cow do I edit the confi/.x*l file?
3he persistent confi#uration for a domain of >ebHo#ic <ervers and clusters is stored in an ^5H
confi#uration file !confi#.xml$. Cou can modify this file in the follo+in# +ays
4sin# the Administration .onsole.
If you +ant to create scripts that automate domain mana#ement, use the +eblo#ic.Admin
utility. <ee =+eblo#ic.Admin .ommand0Hine 1eference=.
If you +ant to create *ava0based mana#ement applications, use the *ava 5ana#ement
-xtensions !*5^$ Application/ro#rammin# Interface !A/I$. <ee the /ro#rammin# >ebHo#ic
5ana#ement <ervices +ith *5^ #uide.
If you +ant to edit the confi#.xml file directly !not recommended$, see the ?-A >ebHo#ic
<erver .onfi#uration 1eference.
27.Is there a Duick wa+ to create and start a re*ote )ana/ed "erver?
3he recommended approach is to use the Domain .onfi#uration >iFard, as described in =<ettin# 4p
and <tartin# 5ana#ed <ervers on a 1emote 5achine= in .reatin# >ebHo#ic .onfi#urations 4sin# the
.onfi#uration >iFard at
http77do+nload.oracle.com7docs7cd7-131K6XJ17platform7docsN17conf#+iF7multi.html.
Bor a streamlined approach, follo+ the instructions at =<tartin# 5ana#ed <ervers Brom a >ebHo#ic
<erver <cript= in the Administration .onsole 'nline 2elp.
29.Ihe Iree 8iew pane of the Web#o/ic Console is not visible in *+ browser. Cow do I
enable it?
-nable the <un *ava /lu#0In from the control panel.
2;.What is the i*portance of the -oot Identit+ file and how will +ou create it?
o If you create boot identity file, it +ill not as" the user name and pass+ord at
server startup time.
o .reate a file called boot.properties in the
\D'5AI9X2'5-Miserversi\serverXnameMisecurity directory that contains t+o lines
usernameTusername
pass+ordTpass+ord
o 3he first time you start the server: the server reads the ?oot Identity file and
over+rites it +ith an encrypted version of the username and pass+ord.
o 3hereafter, the server remembers the credentials for subse)uent startup cycles.
2<.What is the )"I *ode in Weblo/ic? Cow can +ou enable and disable this option?
o 5<I is nothin# but 5ana#ed <erver Independence.
o ?y default, 5ana#ed <ervers can function independently of the Administration <erver.
o A 5ana#ed <erver instance can start in 5<I mode if the Administration <erver is
unavailable.
o .onfi#ure 5<I mode from the Administration .onsole.
o 3o start a 5ana#ed <erver in 5<I mode, perform the follo+in#
-nsure that the 5ana#ed <erverAs root directory contains the confi#
subdirectory.
If the confi# subdirectory does not exist, copy it from the Administration
<erverAs root directory.
<tart the 5ana#ed <erver at the command line or by usin# a script.
o -nvironment M <ervers M <erverX9ame M 3unin# M Advanced M 5ana#ed
<erver Independence -nabled chec" box.
2>.If the Ad*inistration server not available while startin/ the )ana/ed server which is
alread+ enabled )"I$ what are the files it will look for?
o If the Administration <erver is unavailable at boot time, 5ana#ed <ervers search for
confi#.xml
<erialiFed<ystemIni.dat
boot.properties!optional$
o -ach 5ana#ed <erver loo"s in its local confi# directory for confi#.xml, a replica of the
domainAs confi#.xml.
o Cou cannot chan#e the confi#uration of the 5ana#ed <erver that is runnin# in 5<I
mode until it restores communication +ith the Administration <erver.
0@.What if Ad*inistration server /oes down? What is the behavior of the *ana/ed servers?
What are all the thin/s will available or not available?
o 3he Administration <erver
.an #o do+n +ithout affectin# the operation of the 5ana#ed <ervers
.an be restarted +hen the 5ana#ed <ervers are still runnin#
o >hen an Administration <erver #oes do+n
3he domain lo# entries are unavailable +hile it is do+n
5ana#ed <ervers can start in independent mode
3he Administration .onsole and the mana#ement tools are unavailable
01.If an ad*inistration server runnin/ *achine /ot crashed$ how will +ou restart the server
with sa*e confi/uration on new *achine?
o 'racle >ebHo#ic <erver allo+s the creation of a bac"up of the server as follo+s
Install 'racle >ebHo#ic <erver on a bac"up machine.
.opy the application files to a bac"up machine.
.opy the confi#uration files to a bac"up machine.
1estart the Administration <erver on a ne+ machine.
o 3he ne+ Administration <erver contacts the 5ana#ed <ervers and informs them that it
is runnin# on a ne+ I/ address.
02.Cow can +ou run )ultiple Weblo/ic server instances in a sa*e ph+sical *achine?
o Cou can run multiple instances of >H< usin# different confi#urations on the same
physical machine at the same time by either
Assi#nin# multiple I/ addresses to a machine !multihomin#$ and definin# each
server to use a uni)ue I/ address
<pecifyin# the same I/ address but usin# different listen ports
o A multihomed machine
Is a machine +ith multiple I/ addresses
.an run a different >H< instance that is bound to each I/ address
.an be used to confi#ure a cluster on a sin#le machine
00.Cow will +ou create ,o*ain Ie*plate? !xplain briefl+?
o A domain template defines the full set of resources +ithin a domain.
o 'racle provides sample templates for creatin# any platform domain.
o 3here are three +ays to create domain templates
>H<3 offline command line tool
pac" command
Domain 3emplate ?uilder !confi#Xbuilder.sh under >HX2'5-7common7bin$
o 4se the Domain 3emplate ?uilder to create a domain template or an extension
template.
o 4sin# the Domain 3emplate ?uilder
Define a domain and replicate it across multiple pro(ects
Distribute a domain pac"ed +ith an application that has been developed to run
in it
03.What are the default Weblo/ic provided ?roups for securit+ real*?
Administrators
Deployers
'perators
5onitors
App3esters
.rossDomain.onnectors
Admin.hannel4sers
07.What are the default Weblo/ic provided :oles for securit+ real*?
Admin
Deployer
'perator
5onitor
App3ester
.rossDomain.onnectors
Admin.hannel4sers
Anonymous
09.What is the default Weblo/ic provided do*ain te*plate file na*e and location?
>ls.(ar is the default domain template and the location is >HX2'5-icommonitemplatesidomains
0;.What are the ele*ents of the Ad*inistration console?
.han#e .enter
Domain <tructure
2o+ do I_
3ool ?ar
?readcrumb 9avi#ation
<ystem <tatus
0<.What are the 'ode ele*ents of the Ad*inistration console or ,o*ain "tructure?
-nvironment !<ervers, .lusters, Lirtual 2osts, 5i#ratable 3ar#ets, 5achines _$
Deployment
<ervices !5essa#in#, *D?., /ersistent <tore, *3A, Bile 33, (.'5 _$
<ecurity 1ealms
Interoperability
Dia#nostics !Ho# Biles, Dia#nostics 5odules, Dia#nostics Ima#es, Archives, .ontext$
0>.What are the Iool -ar ele*ents in Weblo/ic?
>elcome 5essa#e
.onnected to
2ome
Ho# 'ut
/references
1ecord
2elp
<earch
3@.Cow will +ou enable the Ad*inistration Console?
?y default, the Administration .onsole is enabled. If you disable it, you can re0enable it usin# the
>ebHo#ic <criptin# 3ool !>H<3$. <tart the Administration <erver, then invo"e >H<3 and use the
follo+in# commands
4sin# >H<3 to 1e0enable the .onsole
connect!=username=,=pass+ord=$
edit!$
start-dit!$
cmo.set.onsole-nabled!true$
save!$
activate!$
3he follo+in# attribute!s$ have been chan#ed on 5?eans +hich re)uire server re0start.5?ean
.han#ed com.bea9ameTmydomain,3ypeTDomain Attributes chan#ed
.onsole-nabled
Activation complete
ddisconnect!$
exit!$
31.Cow will +ou !nable and disable the do*ain confi/uration lock?
3he Administration .onsole .han#e .enter provides a +ay to loc" a domain confi#uration so you can
ma"e chan#es to the confi#uration +hile preventin# other accounts from ma"in# chan#es durin# your
edit session.
3he domain confi#uration loc"in# feature is al+ays enabled in production domains. It can be enabled
or disabled in development domains. It is disabled by default +hen you create a ne+ development
domain.
3o enable or disable the domain confi#uration loc"in# feature in a development domain
In the banner toolbar re#ion at the top of the ri#ht pane of the .onsole, clic" /references.
.lic" 4ser /references.
<elect or clear Automatically Ac)uire Hoc" and Activate .han#es to enable or disable
the feature.
.lic" <ave.
After you finish
>hen you enable domain confi#uration loc"in#, you must use the .han#e .enter to loc" and edit
for the domain confi#uration.
32.What are ,+na*ic and 'onJ,+na*ic Chan/es in the Weblo/ic Console? what is the
difference?
<ome chan#es you ma"e in the Administration .onsole ta"e place immediately +hen you activate
them. 'ther chan#es re)uire you to restart the server or module affected by the chan#e. 3hese latter
chan#es are called non0dynamic chan#es. 9on0dynamic chan#es are indicated in the Administration
.onsole +ith this +arnin# icon,.
.han#es to dynamic confi#uration attributes become available once they are activated, +ithout
restartin# the affected server or system restart. 3hese chan#es are made available to the server and
run0time hierarchies once they are activated. .han#es to non0dynamic confi#uration attributes re)uire
that the affected servers or system resources be restarted before they become effective.
If a chan#e is made to a non0dynamic confi#uration settin#, no chan#es to dynamic confi#uration
settin#s +ill ta"e effect until after restart. 3his is to assure that a batch of updates havin# a
combination of dynamic and non0dynamic attribute edits +ill not be partially activated.
9ote that >ebHo#ic <erverAs chan#e mana#ement process applies to chan#es in domain and server
confi#uration data, not tosecurity or application data.
30.What is the infor*ation is /oin/ to store in the Psecurit+Q folder of the ,o*ain director+
contents?
3his directory holds the security0related files that are the same for every >ebHo#ic <erver instance
in the domain
<erialiFed<ystemIni.dat
3his directory also holds security0related files that are only needed by the domainAs Administration
<erver
DefaultAuthoriFerInit.ldift
DefaultAuthenticatorInit.ldift
Default1ole5apperInit.ldift
33.What is the use of "eriali=ed"+ste*Ini.dat file in Weblo/ic?
It is important to protect pass+ords that are used to access resources in a >ebHo#ic <erver domain.
In the past, usernames and pass+ords +ere stored in clear text in a >ebHo#ic security realm. 9o+ all
the pass+ords in a >ebHo#ic <erver domain are hashed. 3he <erialiFed<ystemIni.dat file contains the
hashes for the pass+ords. It is associated +ith a specific >ebHo#ic <erver domain so it cannot be
moved from domain to domain.
If the <erialiFed<ystemIni.dat file is destroyed or corrupted, you must reconfi#ure the >ebHo#ic
<erver domain. 3herefore, you should ta"e the follo+in# precautions
5a"e a bac"up copy of the <erialiFed<ystemIni.dat file and put it in a safe location.
<et permissions on the <erialiFed<ystemIni.dat file such that the system administrator of a >ebHo#ic
<erver deployment has +rite and read privile#es and no other users have any privile#es.
37.!xplain about ,o*ain ,irector+ Contents?
?y default, >ebHo#ic <erver creates domain directories under the ?-AX2'5-7userXpro(ects7domains
directory. 3his section describes the contents of the domain directory and its subfolders. In this
section, domain0name, deployment0name, and server0name represent names that you define +hen
you create a domain.
Individual applications in a domain mi#ht create additional files and directories in the
domain directory.
If you have not yet created a domain, you can see an example of an existin# domain directory by
loo"in# in >HX2'5-7examples7domains7+lXserver +here >HX2'5- is the directory in +hich you
installed >ebHo#ic <erver.
,o*ainJna*e
3he name of this directory is the name of the domain.
autodeplo+
3his directory provides a )uic" +ay to deploy applications in a development server. >hen the
>ebHo#ic <erver instance is runnin# in development mode, it automatically deploys
any applications or modules that you place in this directory.
3he files you place in this directory can be *ava -- applications, such as
An -A1 file
A >A1, -*? *A1, 1A1, or .A1 archived module
An exploded archive directory for either an application or a module

-in
3his directory contains scripts that are used in the process of startin# and stoppin# the Administration
<erver and the 5ana#ed <ervers in the domain. 3hese scripts are #enerally provided as .sh files for
49I^ and .cmd files for >indo+s. 3he bin directory can optionally contain other scripts of domain0+ide
interest, such as scripts to start and stop database mana#ement systems, full0text search en#ine
processes, etc.
Confi/
3his directory contains the current confi#uration and deployment state of the domain. 3he central
domain confi#uration file, confi#.xml, resides in this directory.
Confi/Bconfi/Cache
.ontains data that is used to optimiFe performance +hen validatin# chan#es in the domainAs
confi#uration documents. 3his data is internal to >ebHo#ic <erver and does not need to be bac"ed up.
Confi/Bdia/nostics
3his directory contains system modules for instrumentation in the >ebHo#ic Dia#nostic Brame+or".
Confi/Bjdbc
3his directory contains system modules for *D?. #lobal *D?. modules that can be confi#ured directly
from *5^ !as opposed to *<10NN$.
Confi/Bj*s
3his directory contains system modules for *5< #lobal *5< modules that can be confi#ured directly
from *5^ !as opposed to *<10NN$.
Confi/Blib
3his directory is not used in the current release of >ebHo#ic <erver.
Confi/Bnode*ana/er
3his directory holds confi#uration information for connection to the 9ode 5ana#er.
Confi/Bsecurit+
3his directory contains system modules for the security frame+or". It contains one security provider
confi#uration extension for each "ind of security provider in the domainAs current realm.
Confi/Bstartup
3his directory contains system modules that contain startup plans. <tartup plans are used to #enerate
shell scripts that can be used as part of server startup.
Confi/Archive
3his directory contains a set of *A1 files that save the domainAs confi#uration state. *ust before
pendin# chan#es to the confi#uration are activated, the domainAs existin# confi#uration state,
consistin# of the confi#.xml file and the other related confi#uration files, is saved in a versioned *A1
file +ith a name li"e confi#.(ard1, confi#.(ard2, etc.
3he maximum number of versioned *A1 files to be "ept is specified by the archive.onfi#uration.ount
attribute of Domain5?ean. 'nce this maximum number is reached, the oldest conversion archive is
deleted before a ne+ one is created.
ConsoleJext
3his directory contains extensions to the Administration .onsole, +hich enable you to add content to
the >ebHo#ic <erver Administration .onsole, replace content, and chan#e the lo#os, styles and colors
+ithout modifyin# the files that are installed +ith >ebHo#ic <erver. Bor example, you can add content
that provides custom monitorin# and mana#ement facilities for yourapplications. <ee -xtendin# the
Administration .onsole.
InitJinfo
3his directory contains files used for >ebHo#ic domain provisionin#. Cou should not modify any files in
this directory.
#ib
Any *A1 files you put in this directory are added to the system classpath of each server instance in the
domain +hen the serverAs *ava virtual machine starts.
(endin/
3his directory contains domain confi#uration files representin# confi#uration chan#es that have been
re)uested, but not yet activated. 'nce the confi#uration chan#es have been activated, the
confi#uration files are deleted from this directory.
"ecurit+
3his directory holds those security0related files that are the same for every >ebHo#ic <erver instance
in the domain
<erialiFed<ystemIni.dat
3his directory also holds security0related files that are only needed by the domainAs Administration
<erver
DefaultAuthoriFerInit.ldift
DefaultAuthenticatorInit.ldift
Default1ole5apperInit.ldift

"ervers
3his directory contains one subdirectory for each >ebHo#ic <erver instance in the domain. 3he
subdirectories contain data that is specific to each server instance.
"erversBserverJna*e
3his directory is the server directory for the >ebHo#ic <erver instance +ith the same name as the
directory.
"erversBserverJna*eBbin
3his directory holds executable or shell files that can be or must be different for each server. 3he
server environment script !set<erver-nv.sh or set<erver-nv.cmd$ is an example of a file that resides
here because it can differ from one >ebHo#ic <erver instance to the next, for example, dependin# on
+hether the server instance has its o+n startup plan.
"erversBserverJna*eBcache
3his directory holds directories and files that contain cached data. ?y Zcached[ here +e mean that the
data is a copy, possibly in a processed form !compiled, translated, or reformatted$, of other data.
"erversBserverJna*eBcacheB!6-Co*pilerCache
3his directory is a cache for compiled -*?s.
"erversBserverJna*eBdata
3his directory holds files that maintain persistent per0server state used to run the >ebHo#ic <erver
instance, other than security state, as opposed to temporary, cached or historical information. Biles in
this directory are important data that must be retained as the >ebHo#ic <erver instance is brou#ht up,
is brou#ht do+n, crashes, restarts, or is up#raded to a ne+ version.
"erversBserverJna*eBdataBldap
3his directory holds the embedded HDA/ database. 3he run0time security state for the >ebHo#ic
<erver instance is persisted in this directory.
"erversBserverJna*eBdataBstore
3his directory holds >ebHo#ic persistent stores. Bor each persistent store, there is a subdirectory that
holds the files that represent the persistent store. 3he name of the subdirectory is the name of the
persistent store. ?y convention there is one store named default.
"erversBserverJna*eBlo/s
3his directory holds lo#s and dia#nostic information. 3his information is historical in nature. It is not
crucial to the operation of the server, and can be deleted !+hile the >ebHo#ic <erver instance is
do+n, at least$ +ithout affectin# proper operation. 2o+ever, the information can be )uite useful for
debu##in# or auditin# purposes and should not be deleted +ithout #ood reason.
"erversBserverJna*eBlo/sBdia/nosticTi*a/es
3his directory holds information created by the <erver Ima#e .apture component of the >ebHo#ic
Dia#nostic Brame+or".
"erversBserverJna*eBlo/sBj*s"ervers
3his directory contains one subdirectory for each *5< server in the >ebHo#ic <erver instance. -ach
such subdirectory contains the lo#s for that *5< server. 3he name of the subdirectory is the name of
the *5< server.
"erversBserverJna*eBlo/sBconnector
3his directory is the default base directory for connector module !*.A 1esourceAdapter$ lo#s.
"erversBserverJna*eBsecurit+
3his directory holds security0related files that can be or must be different for each >ebHo#ic <erver
instance. 3he file boot.properties is an example of a file that resides here because it can differ from
one server to the next. 3his directory also maintains files related to <<H "eys.
"erversBserverJna*eBt*p
3his directory holds temporary directories and files that are created +hile a server instance is runnin#.
Bor example, a *5< pa#in# directory is automatically created here unless another location is specified.
Biles in this directory must be left alone +hile the server is runnin#, but may be freely deleted +hen
the server instance is shut do+n.
I*p
3his directory stores temporary files used in the chan#e mana#ement process. Cou should not modify
any files in this directory.
userTsta/edTconfi/
?y default, confi#uration information is automatically copied from the Administration <erver to each
5ana#ed <erver. If instead you prefer to sta#e confi#uration chan#es manually, you can use this
directory as an alternative to the confi# directory.
39.Cow *an+ wa+s +ou can chan/e the confi/uration chan/es?
3he chan#e mana#ement features of >H<
o -nable you to distribute confi#uration chan#es throu#hout a domain securely,
consistently, and predictably
o Are the same, re#ardless of +hether you are usin#
3he >H< Administration .onsole
3he >ebHo#ic <criptin# 3ool !>H<3$
3he *ava 5ana#ement -xtension !*5^$ A/Is
3;.What is the user of W#"I in Weblo/ic?
o 3he >H< command0line tools are useful
Bor automatin# common administration activities
As an alternative to the Administration .onsole
>hen #raphical tools are not supported
o >H<3 provides a command0line interface for
.reatin# ne+ >H< domains
1etrievin# and updatin# >H< domain confi#urations
Deployin# applications
'btainin# run0time server statistics
3<.Cow *an+ W#"I *odules are there? !xplain?
o %nline *ode
.onnected to a runnin# server
Access to all >H< confi#uration and run0time attributes
.reate and activate chan#e sessions similar to the >H< console
o %ffline *ode
Domain not runnin#
Access to only persisted domain confi#uration !confi#.xml$
.reate or update domains similar to usin# the .onfi#uration >iFard
3>.What is the 'ode )ana/er 1')2? !xplain briefl+?
'ode )ana/er 1')2
o <tarts and stops 5ana#ed <ervers remotely server, domain, and cluster
o Available as either a *ava0based or !for 49I^ or Hinux$ a script0based process
o 5onitors and acts on server health
o 1uns on the same computers as the 5ana#ed <ervers
o .an be run automatically in the bac"#round, as a >indo+s service or a 49I^ daemon
7@.Cow *an+ versions of 'ode )ana/ers are available?
o 3here are t+o versions of 9ode 5ana#er
*ava0based 9ode 5ana#er
<cript0based 9ode 5ana#er
o *ava0based 9ode 5ana#er runs +ithin a *ava Lirtual 5achine !*L5$ process.
o <cript0based 9ode 5ana#er !used only for 49I^ and Hinux systems$ does not have as
much security, but provides the ability to remotely mana#e servers over a net+or"
usin# <ecure <hell !<<2$.
71.Cow 'ode )ana/er will work with the Weblo/ic "erver? Cow will +ou confi/ure 'ode
)ana/er in W#"?
o 9ode 5ana#er must run on each computer that hosts the >H< instances that you +ant
to control +ith 9ode 5ana#er.
o Cou should confi#ure each computer as a machine in 'racle >ebHo#ic <erver, and
assi#n each server instance, +hich is to be controlled by 9ode 5ana#er, to the
machine that the server instance runs on.
o 9ode 5ana#er should run as an operatin# system service, so that it
automatically restarts upon system failure or reboot.
72.What is the 'ode )ana/er ,efault -ehavior?
o After >ebHo#ic <erver is installed, 9ode 5ana#er is Zready0to0run[ if 9ode 5ana#er
and Administration <erver are on the same machine.
o ?y default, the follo+in# behaviors are confi#ured
3he Administration .onsole can use 9ode 5ana#er to start
the 5ana#ed <ervers .
9ode 5ana#er monitors the 5ana#ed <ervers that it started.
3he automatic restart of 5ana#ed <ervers is enabled.
70.Io start 'ode )ana/er at s+ste* start up ti*e$ what we have to do?
>e have to confi#ure 9ode 5ana#er as a 'peratin# <ystem <ervice.
o It is recommended that you run 9ode 5ana#er !95$ as
A >indo+s service on >indo+s platforms and
A daemon on 49I^ platforms
o 1unnin# 95 durin# system startup allo+s it to restart automatically +hen the system
is rebooted.
o 9ode 5ana#er can be confi#ured to start at boot time, as either of these
A >indo+s service
A 49I^ daemon
73.Cow will +ou confi/ure 'ode )ana/er as Windows "ervice?
o -dit install'ode)/r"vc.c*d to specify 9ode 5ana#erAs listen address and listen
port.
o 1un install'ode)/r"vc.c*d to reinstall 9ode 5ana#er as a service, listenin# on the
updated address and port.
o Delete the 9ode 5ana#er <ervice usin# uninstall'ode)/r"vc.c*d.
77.!xplain about Weblo/ic server #o/ )essa/e Gor*at?
>hen a >ebHo#ic <erver instance +rites a messa#e to the server lo# file, the first line of each
messa#e be#ins +ith dddd follo+ed by the messa#e attributes. -ach attribute is contained bet+een
an#le brac"ets.
2ere is an example of a messa#e in the server lo# file
dddd\*an J5, 2J1J 1J4651 A5 -<3M \9oticeM \>ebHo#ic<erverM \5y.omputerM
\examples<erverM \mainM \\>H< IernelMM \M \nullM \1JNJ5&5211KJ4M \?-A0JJJ36JM
\<erver started in 1499I9O modeM In this example, the *essa/e attributes are #ocaleJ
for*atted Ii*esta*p, "everit+, "ubs+ste*, )achine 'a*e, "erver 'a*e, Ihread I,, &ser
I,, Iransaction I,, ,ia/nostic Context I,, :aw Ii*e 8alue, )essa/e I,, and )essa/e Iext.
If a messa#e is not lo##ed +ithin the context of a transaction, the an#le brac"ets for 3ransaction ID
are present even thou#h no 3ransaction ID is present.
If the messa#e includes a stac" trace, the stac" trace is included in the messa#e text.
>ebHo#ic <erver uses the host computerAs default character encodin# for the messa#es it +rites.
79.What is the #o/ )essa/e Gor*ant of %utput to "tandard %ut and "tandard !rror?
>hen a >ebHo#ic <erver instance +rites a messa#e to standard out, the output does not include the
dddd prefix and does not include the <erver 9ame, 5achine 9ame, 3hread ID, 4ser ID, 3ransaction
ID, Dia#nostic .ontext ID, and 1a+ 3ime Lalue fields.
2ere is an example of ho+ the messa#e from the previous section +ould be printed to standard out
\(an J1, 2J1J 1J511J A5 -<3M \9oticeM \>ebHo#ic<erverM \?-A0JJJ36JM \<erver started in
1499I9O modeMIn this example, the messa#e attributes are #ocaleJfor*atted
Ii*esta*p, "everit+, "ubs+ste*, )essa/e I,, and )essa/e Iext.
7;.Cow *an+ lo/ )essa/e "everit+ levels are there in Weblo/ic? !xplain?
3he severity attribute of a >ebHo#ic <erver lo# messa#e indicates the potential impact of the event or
condition that the messa#e reports.
"everit+
)eanin/
31A.- 4sed for messa#es from the Dia#nostic Action Hibrary. 4pon enablin#
dia#nosticinstrumentation of server and application classes, 31A.- messa#es follo+ the
re)uest path of a method.
I9B' 4sed for reportin# normal operations: a lo+0level informational messa#e.
9'3I.- An informational messa#e +ith a hi#her level of importance.
>A19I9O A suspicious operation or confi#uration has occurred but it mi#ht not affect normal
operation.
-11'1 A user error has occurred. 3he system or application can handle the error +ith no
interruption and limited de#radation of service.
.1I3I.AH A system or service error has occurred. 3he system can recover but there mi#ht be a
momentary loss or permanent de#radation of service.
AH-13 A particular service is in an unusable state +hile other parts of the system continue to
function. Automatic recovery is not possible: the immediate attention of the administrator
is needed to resolve the problem.
-5-1O-9.C3he server is in an unusable state. 3his severity indicates a severe system failure or
panic.
D-?4O A debu# messa#e +as #enerated.
7<.What is the default lo/ )essa/e "everit+ levels in Weblo/ic?
>ebHo#ic <erver subsystems #enerate many messa#es of lo+er severity and fe+er messa#es of
hi#her severity. Bor example, under normal circumstances, they #enerate many I'G% messa#es and
no !)!:?!'CY messa#es.
7>.What is the #o/ )essa/e "everit+ #evel seDuence fro* lowest to hi/hest i*pact?
A lo# level ob(ect can specify any of the follo+in# values, from lo+est to hi#hest impact
31A.-, D-?4O, I9B', 9'3I.-, >A19I9O, -11'1, .1I3I.AH, AH-13, -5-1O-9.C
9@.Cow will +ou specif+ the lo//in/ i*ple*entation in Weblo/ic?
>e +ill specify the lo##in# implementation usin# =6ava #o//in/ A(I= or =#o/3j= in >eblo#ic.
About #o/3j
Ho#4( has three main components lo//ers$ appenders$ and la+outs. 3he follo+in# sections provide
a brief introduction to Ho#4(.
#o//ers
Ho#4( defines a Ho##er class. An application can create multiple lo##ers, each +ith a uni)ue name. In
a typical usa#e of Ho#4(, anapplication creates a Ho##er instance for each application class that +ill
emit lo# messa#es. Ho##ers exist in a namespace hierarchy and inherit behavior from their ancestors
in the hierarchy.
Appenders
Ho#4( defines appenders !handlers$ to represent destinations for lo##in# output. 5ultiple appenders
can be defined. Bor example, an application mi#ht define an appender that sends lo# messa#es to
standard out, and another appender that +rites lo# messa#es to a file. Individual lo##ers mi#ht be
confi#ured to +rite to Fero or more appenders. 'ne example usa#e +ould be to send all lo##in#
messa#es !all levels$ to a lo# file, but only -11'1 level messa#es to standard out.
#a+outs
Ho#4( defines layouts to control the format of lo# messa#es. -ach layout specifies a particular
messa#e format. A specific layout is associated +ith each appender. 3his lets you specify a different
lo# messa#e format for standard out than for file output, for example.
6ava #o//in/ A(I
>ebHo#ic lo##in# services provide the .ommons Ho#Bactory and Ho# interface implementations that
direct re)uests to the underlyin# lo##in# implementation bein# used by >ebHo#ic lo##in# services.
3o use .ommons Ho##in#, put the >ebHo#ic0specific .ommons classes,
W?-AX2'5-7modules7com.bea.core.+eblo#ic.commons.lo##in#X1.3.J.J.(ar, to#ether +ith the
commons0lo##in#.(ar file in one of the follo+in# locations
A//0I9B7HI? or >-?0I9B7HI? directory
D'5AI9X9A5-7HI? directory
<erver .HA<</A32
9ote >ebHo#ic <erver does not provide a .ommons lo##in# version in its distribution.
91.What is the user of #o/ Gilters in Weblo/ic?
Ho# filters
o .ontrol the lo# messa#es that #et published
o Are based on the values of messa#e attributes
o .an be applied to different messa#e destinations
<erver lo# file
<erver memory buffer
<erver standard out
Domain lo# file
92.What is the user of 'etwork channels in Weblo/ic?
Adds flexibility to the net+or"in# confi#uration
o 5ultiple 9I.s for a sin#le >H< server
o <pecific 9I.s or multiple port numbers on a 9I. for specific >H< servers
o Ability to use multiple I/ addresses +ith each server
o Ability to use a sin#le I/ address +ith multiple ports
o Ability to confi#ure the cluster multicast port number independently of the port
numbers used by the cluster members
o 5ultiple <<H confi#urations on one server
9et+or" channels
o Define the set of basic attributes of a net+or" connection to >H<
o .an assi#n multiple channels to a sin#le server !se#ment net+or" traffic$
o .an prioritiFe internal !non041H$ connections
o .an separate incomin# client traffic from internal server to server traffic in a domain
o A Zdefault[ channel #ets #enerated +hen a server is created.
90.Cow will +ou confi/ure a web application in Weblo/ic?
>eb applications are confi#ured usin# the +eb.xml and +eblo#ic.xml deployment descriptors, +hich
Define the run0time environment
5ap 41Hs to servlets and *</s
Define application defaults such as +elcome and error pa#es
<pecify *2-- security constraints
Define +or" mana#ers for applications
<et the context root for the application
93.What infor*ation will be available in Pweb.x*lQ file?
3he +eb.xml file is a deployment descriptor that is used to confi#ure the follo+in#
<ervlets and *</ re#istration
<ervlet initialiFation parameters
*</ ta# libraries
5I5- type mappin#s
>elcome file list
-rror pa#es
<ecurity constraints and roles
1esources
-*? references
97.What infor*ation will be available in Pweblo/ic.x*lQ file?
4sin# +eblo#ic.xml, you can confi#ure the follo+in#
3he applicationAs root context path
Application lo##in#
<ecurity role mappin#s
Advanced session settin#s
<ession clusterin#
1eferences to shared libraries
1eferences to server resources !data sources, -*?s, and so on$
>or" mana#ers and threadin#
Lirtual directories
*</ compiler options
99.Io confi/ure a Pweb serviceQ Applications in Weblo/ic$ what are all the
files reDuired as a deplo+*ent descriptor?
A >eb service application
1esponds to 233/ client re)uests usin# the <imple 'b(ect Access
/rotocol !<'A/$
4ses the same structure as a *ava -- >eb application
<upports t+o additional deployment descriptors
+ebservices.xml
+eblo#ic0+ebservices.xml
9;. What is the 8irtual director+ )appin/s? Which file +ou are /oin/ to
provide these virtual director+ *appin/s?
Lirtual directories
.an be used to refer to physical directories
-nable you to avoid the need to hard code paths to physical directories
Allo+ multiple >eb applications to share common physical directories
for specific re)uests such as ima#es
Decrease duplication of files across applications
Are confi#ured in +eblo#ic.xml
!xa*ple
\virtual0directory0mappin#M
\local0pathMc7usr7#ifs\7local0pathM
\url0patternM7ima#es78\7url0patternM
\url0patternM8.(p#\7url0patternM
\7virtual0directory0mappin#M
\virtual0directory0mappin#M
\local0pathMc7usr7commonX(sps.(ar\7local0pathM
\url0patternM8.(sp\7url0patternM
\7virtual0directory0mappin#M
9<.What is the deplo+*ent descriptor file for ejb applications? What are all
the infor*ation is /oin/ to provide in that file?
-(b application deployment descriptor file in >eblo#ic is Z+eblo#ic0e(b0(ar.xml[.
4sin# +eblo#ic0e(b0(ar.xml, you can confi#ure the follo+in#
<ecurity role mappin#s
Advanced security settin#s
-*? clusterin#
-*? poolin# and cachin#
>or" mana#ers and threadin#
9>.What is an !nterprise Application?
An enterprise application is a #roupin# of several resources into one
deployable unit that is pac"a#ed in an .ear file.
3hese resources include
>eb applications !.+ar$
-*? applications !.(ar$
*ava applications !.(ar$
1esource adapters !.rar$
;@.What is the user of !nterprise Applications?
4se enterprise applications to
Avoid namespace clashes
Declare application +ide security roles
Deploy an application as one unit
<hare application +ide -*? resources
.onfi#ure local *D?. data sources
.onfi#ure local *5< resources
.onfi#ure local ^5H resources
;1.What is the user of Pweblo/icJapplication.x*lQ deplo+*ent descriptor file?
4sin# +eblo#ic0application.xml, you can confi#ure
o 1eferences to shared libraries
o >or" mana#ers and threadin#
o Default -*? and >eb application parameter values
>e can confi#ure enterprise +ide >H<0specific features +ith the +eblo#ic0application.xml deployment
descriptor
o ^5H parsers
o ^5H entity mappin#s
o *D?. data sources
o *5< connection factories and destinations
o <ecurity realms
;2.What is the user of Weblo/ic shared java !! #ibraries?
A <hared *ava -- library
o Is a reusable portion of a >eb or enterprise application
o Is referenced by other deployed applications
o Avoids duplicatin# source files amon# *ava -- pro(ects
o .an contain deployment descriptors that are mer#ed +ith the applicationAs descriptors
;0.!xplain about deplo+*ent *ethods in Weblo/ic?
o >H< supports three deployment methods
Auto0deployment
.onsole deployment
.ommand0line deployment
o Cou can deploy
-nterprise, >eb, and -*? applications
>eb services
*2-- libraries
*D?., *5<, and Dia#nostic Brame+or" modules
1esource adapters
'ptional pac"a#es
.lient application archives
o Applications and -*?s can be deployed
In an archived file !.ear, .+ar, .(ar$
In an exploded !open$ directory format
;3.Cow *an+ wa+s we can deplo+ an application to Weblo/ic servers?
<everal methods are available to deploy the 'racle >ebHo#ic <erver applications and shared libraries,
includin#
o Administration .onsole
o >ebHo#ic <criptin# 3ool !>H<3$
o +eblo#ic.Deployer *ava class
o +ldeploy Ant tas"
o Auto0deployment folder
;7.!xplain about auto deplo+*ent in Weblo/ic?
If /roduction 5ode is 'BB
o Cou can install an application simply by copyin# it !manually or usin# the console$ to
the Zautodeploy[
directory of the domain
o 3he Administration <erver monitors this directory for ne+, chan#ed, or
removed applications
o 3his confi#ures, tar#ets, and deploys the application only to the Administration <erver
Hocation of Applications Directory
W?-AX2'5-7userXpro(ects7domains7domain/name7autodeploy
;9.!xplain about Gast"wap and %nJ,e*and ,eplo+*ent in Weblo/ic?
o >ebHo#icAs Bast<+ap feature is
-nabled usin# the >ebHo#ic deployment descriptors
Available only if the domain is not runnin# in production mode
Applicable only to >eb applications that are not archived
o >hen enabled
>ebHo#ic automatically reloads the modified *ava class files +ithin applications
Developers can perform iterative development +ithout an explicit
redeployment
'n0demand deployment
-xcerpt from +eblo#ic.xml
\fast0s+apMtrue\7fast0s+apM
;;.While deplo+in/ an application to Weblo/ic$ what is the difference between ,evelop*ent
and (roduction )ode?
o An Administration <erver starts usin# either
3he development mode, +hich turns auto0deployment on
3he production mode, +hich turns auto0deployment off
o 3he Administration <erver starts in the mode selected at domain creation time.
o 3he mode is set for all 'racle >ebHo#ic <ervers in a #iven domain.
;<.!xplain about console deplo+*ent *ethod?
Deployin# +ith the console allo+s full administrator control
o Installation from a location of your choice
o 5anual confi#uration of application name
o 3ar#etin# of application to individual servers and7or clusters
o .onfi#urin# the application +ithout tar#etin# it
o Activatin# deployment +hen desired
;>.!xplain about co**and line deplo+*ent?
o 3he +eblo#ic.Deployer utility allo+s you to perform deployment operations similar to
those available in the console.
o +eblo#ic.Deployer actions can also be scripted +ith the Ant tas" +ldeploy.
weblo/ic.,eplo+er "+ntax
Y (ava +eblo#ic.Deployer RoptionsS
R0deploye0undeploye0redeploye0starte0stope0listappsS Rfile!s$S
(repare and deplo+ a new application
(ava +eblo#ic.Deployer 0adminurl t377adminserver&JJ1
0username myuser Vpass+ord mypass Vname 21<ervices
0source 7usr721<ervices.ear 0tar#ets serverA Wdeplo+
:edeplo+ an application
(ava +eblo#ic.Deployer 0adminurl t377adminserver&JJ1
0username myuser Vpass+ord mypass Vname 21<ervices
Wredeplo+
&ndeplo+ an application
(ava +eblo#ic.Deployer 0adminurl t377adminserver&JJ1
0username myuser Vpass+ord mypass Vname 21<ervices
Wundeplo+
#ist all applications
(ava +eblo#ic.Deployer 0adminurl t377adminserver&JJ1
0username myuser Vpass+ord mypass Jlistapps
<@.What is 6',I?
o 3he *ava 9amin# and Directory Interface is an A/I for uniformly accessin# the
different namin# and directory services.
o 3his is a ma(or step for+ard because
Different services use vastly different namin# schemes
*ava applications can no+ navi#ate seamlessly across databases, files,
directories, ob(ects, and net+or"s
;1.What is the user of Pweblo/icJapplication.x*lQ deplo+*ent descriptor file?
4sin# +eblo#ic0application.xml, you can confi#ure
o 1eferences to shared libraries
o >or" mana#ers and threadin#
o Default -*? and >eb application parameter values
>e can confi#ure enterprise +ide >H<0specific features +ith the +eblo#ic0application.xml deployment
descriptor
o ^5H parsers
o ^5H entity mappin#s
o *D?. data sources
o *5< connection factories and destinations
o <ecurity realms
;2.What is the user of Weblo/ic shared java !! #ibraries?
A <hared *ava -- library
o Is a reusable portion of a >eb or enterprise application
o Is referenced by other deployed applications
o Avoids duplicatin# source files amon# *ava -- pro(ects
o .an contain deployment descriptors that are mer#ed +ith the applicationAs descriptors
;0.!xplain about deplo+*ent *ethods in Weblo/ic?
o >H< supports three deployment methods
Auto0deployment
.onsole deployment
.ommand0line deployment
o Cou can deploy
-nterprise, >eb, and -*? applications
>eb services
*2-- libraries
*D?., *5<, and Dia#nostic Brame+or" modules
1esource adapters
'ptional pac"a#es
.lient application archives
o Applications and -*?s can be deployed
In an archived file !.ear, .+ar, .(ar$
In an exploded !open$ directory format
;3.Cow *an+ wa+s we can deplo+ an application to Weblo/ic servers?
<everal methods are available to deploy the 'racle >ebHo#ic <erver applications and shared libraries,
includin#
o Administration .onsole
o >ebHo#ic <criptin# 3ool !>H<3$
o +eblo#ic.Deployer *ava class
o +ldeploy Ant tas"
o Auto0deployment folder
;7.!xplain about auto deplo+*ent in Weblo/ic?
If /roduction 5ode is 'BB
o Cou can install an application simply by copyin# it !manually or usin# the console$ to
the Zautodeploy[
directory of the domain
o 3he Administration <erver monitors this directory for ne+, chan#ed, or removed
applications
o 3his confi#ures, tar#ets, and deploys the application only to the Administration <erver
Hocation of Applications Directory
W?-AX2'5-7userXpro(ects7domains7domain/name7autodeploy
;9.!xplain about Gast"wap and %nJ,e*and ,eplo+*ent in Weblo/ic?
o >ebHo#icAs Bast<+ap feature is
-nabled usin# the >ebHo#ic deployment descriptors
Available only if the domain is not runnin# in production mode
Applicable only to >eb applications that are not archived
o >hen enabled
>ebHo#ic automatically reloads the modified *ava class files +ithin applications
Developers can perform iterative development +ithout an explicit
redeployment
'n0demand deployment
-xcerpt from +eblo#ic.xml
\fast0s+apMtrue\7fast0s+apM
;;.While deplo+in/ an application to Weblo/ic$ what is the difference between ,evelop*ent
and (roduction )ode?
o An Administration <erver starts usin# either
3he development mode, +hich turns auto0deployment on
3he production mode, +hich turns auto0deployment off
o 3he Administration <erver starts in the mode selected at domain creation time.
o 3he mode is set for all 'racle >ebHo#ic <ervers in a #iven domain.
;<.!xplain about console deplo+*ent *ethod?
Deployin# +ith the console allo+s full administrator control
o Installation from a location of your choice
o 5anual confi#uration of application name
o 3ar#etin# of application to individual servers and7or clusters
o .onfi#urin# the application +ithout tar#etin# it
o Activatin# deployment +hen desired
;>.!xplain about co**and line deplo+*ent?
o 3he +eblo#ic.Deployer utility allo+s you to perform deployment operations similar to
those available in the console.
o +eblo#ic.Deployer actions can also be scripted +ith the Ant tas" +ldeploy.
weblo/ic.,eplo+er "+ntax
Y (ava +eblo#ic.Deployer RoptionsS
R0deploye0undeploye0redeploye0starte0stope0listappsS Rfile!s$S
(repare and deplo+ a new application
(ava +eblo#ic.Deployer 0adminurl t377adminserver&JJ1
0username myuser Vpass+ord mypass Vname 21<ervices
0source 7usr721<ervices.ear 0tar#ets serverA Wdeplo+
:edeplo+ an application
(ava +eblo#ic.Deployer 0adminurl t377adminserver&JJ1
0username myuser Vpass+ord mypass Vname 21<ervices
Wredeplo+
&ndeplo+ an application
(ava +eblo#ic.Deployer 0adminurl t377adminserver&JJ1
0username myuser Vpass+ord mypass Vname 21<ervices
Wundeplo+
#ist all applications
(ava +eblo#ic.Deployer 0adminurl t377adminserver&JJ1
0username myuser Vpass+ord mypass Jlistapps
<@.What is 6',I?
o 3he *ava 9amin# and Directory Interface is an A/I for uniformly accessin# the
different namin# and directory services.
o 3his is a ma(or step for+ard because
Different services use vastly different namin# schemes
*ava applications can no+ navi#ate seamlessly across databases, files,
directories, ob(ects, and net+or"s
<1.Wh+ the 6',I reDuired in Weblo/ic?
In 'racle >ebHo#ic <erver, *9DI serves as a repository and loo"up service for *2-- ob(ects, includin#
o -nterprise *ava?eans !-*?$ home stubs
o *D?. Data<ources
o *5< connection factories, )ueues, and topics
o 1emote 5ethod Invocation !15I$ stubs
<2.What is the use of 'a*in/ "ervices?
A namin# service provides a method for mappin# identifiers to entities or ob(ects.
Ier*
,efinition !xa*ple
?indin#
3he association of an atomic name and
an ob(ect
+++.example.com is bound to
2JK.1J.21&.3N.
9amespace
A set of uni)ue names in a namin#
system
+++.example.com7 products
<0.!xplain about Contexts and "ubJcontexts in 6',I?
o <ubcontexts are referenced throu#h the dot delimiters !.$.
o 3he subcontexts must be created before ob(ects are placed into them.
o 3ypically +hen ob(ects are bound to a *9DI tree, subcontexts are automatically
created based on the *9DI name.
If the follo+in# context exists com.oracle.examples
Cou cannot bind com.oracle.examples.e(b.<ome'b(ect
>ithout first creatin# com.oracle.examples.e(b
<3.Cow can I set deplo+*ent order for applications?
>ebHo#ic <erver N.1 allo+s you to select the load order for applications. <ee the Application5?ean
Hoad'rder attribute inApplication. >ebHo#ic <erver deploys server0level resources !first *D?. and
then *5<$ before deployin# applications.Applications are deployed in this order connectors, then
-*?s, then +eb Applications. If the application is an -A1, the individual components are loaded in the
order in +hich they are declared in the application.xml deployment descriptor.
<7.Can I refresh static co*ponents of a deplo+ed application without havin/ to redeplo+ the
entire application?
Ces. Cou can use +eblo#ic.Deployer to specify a component and tar#et a server, usin# the follo+in#
syntax
(ava +eblo#ic.Deployer 0adminurl http77admin&JJ1 0name appname 0tar#ets server1,server2
0deploy (sps78.(sp
<9.When should I use the Jnosta/e option?
<et the sta#in# mode to 0nosta#e !usin# +eblo#ic.Deployer or the Administration .onsole$ if you don%t
+ant to copy deployment files but +ant to deploy an application from its present location. All tar#et
servers must be able to access the same set of deployment files.
<;.When should I use the externalTsta/e option?
<et 0externalXsta#e usin# +eblo#ic.Deployer if you +ant to sta#e the application yourself, and prefer
to copy it to its tar#et by your o+n means.
<<.What are the ,eplo+*ent Iools for ,evelopers?
>ebHo#ic <erver provides several tools for deployin# applications and stand0alone modules
+ldeploy is an Ant tas" version of the +eblo#ic.Deployer utility. Cou can automate deployment
tas"s by placin# +ldeploy commands in an Ant build.xml file and runnin# Ant to execute the
commands.
+eblo#ic./lanOenerator is a command0line tools that enables developers to export
an applicationAs confi#uration for deployment to multiple >ebHo#ic <erver environments.
3he deployment A/I allo+s you to perform deployment tas"s pro#rammatically usin# *ava
classes.
3he autodeploy domain directory allo+s you to deploy an application )uic"ly for evaluation or
testin# in a development environment.
<>.What is the ,eplo+*ent order of Weblo/ic "erver at "erver "tartup ti*e?
?y default, >ebHo#ic <erver deploys applications and resources in the follo+in# order
*D?. system modules
*5< system modules
*2-- Hibraries and optional pac"a#es
Applications and stand0alone modules
<tartup classes
9ote >ebHo#ic <erver security services are al+ays initialiFed before server resources, applications,
and startup classes are deployed. Bor this reason, you cannot confi#ure custom security providers
usin# startup classes, nor can custom security provider implementations rely on deployed server
resources such as *D?..
>@.Cow will +ou PFill the 68)Q or runnin/ Weblo/ic server in different operatin/ s+ste*s?
-ach >ebHo#ic <erver instance runs in its o+n *L5. If you are unable to shut do+n a server instance
usin# the scripts +hich are provided by the >eblo#ic !stop>eblo#ic.cmd7 stop5ana#ed>eblo#ic.cmd$,
you can use an operatin# system command to "ill the *L5.
.aution If you "ill the *L5, the server immediately stops all processin#. Any session data is lost. If
you "ill the *L5 for an Administration <erver +hile the server is +ritin# to the confi#.xml file, you can
corrupt the confi#.xml file.
"o*e co**on wa+s to kill the 68) are as follows
If the shell !command prompt$ in +hich you start the server is still open, you can type .trl0..
'n a >indo+s computer , you can use the 3as" 5ana#er to "ill a *L5.
'n a 49I^ computer, you can use the Zps[ command to list all runnin# processes. 3hen you can use
the "ill command to "ill the *L5 .
>1. Can I /enerate deplo+*ent descriptor files auto*aticall+?
Ces, >ebHo#ic ?uilder automatically #enerates deployment descriptor files for your *2-- applications.
<ee >ebHo#ic ?uilder 'nline 2elp.
>2.Can I set the deplo+*ent order for application *odules? Gor standalone *odules?
3he Hoad 'rder attribute controls the deployment order of standalone modules
and applications relative to other modules andapplications of the same type.
Bor example, standalone -*?s +ith smaller Hoad 'rder values are deployed before those +ith hi#her
values.
5odules that are deployed as part of an -nterprise Application !-A1 file or directory$ are deployed in
the order in +hich they are specified in the application.xml deployment descriptor.
>0.What is the difference between the W#TC%)!Bconfi/Bexa*plesBapplications folder and
the W#TC%)!Bconfi/Bexa*plesBsta/e folder?
3he applications folder is intended for applications that are not yet ready for a production
environment. >ebHo#ic <erver dynamically deploys the contents of the applications folder. 3he sta#e
folder !or a folder that you create for the same purpose$ is for storin# copies of deployment files that
are ready for deployment in a production environment !deployments that use the sta#e or
externalXsta#e deployment modes$.
>3.Cow do I turn the autoJdeplo+*ent feature off?
3he auto0deployment feature chec"s the applications folder every three seconds to determine +hether
there are any ne+applications or any chan#es to existin# applications and then dynamically deploys
these chan#es.
3he auto0deployment feature is enabled for servers that run in development mode. 3o disable auto0
deployment feature, use one of the follo+in# methods to place servers in production mode
In the Administration .onsole, clic" the name of the domain in the left pane, then select the
/roduction 5ode chec"box in the ri#ht pane.
At the command line, include the follo+in# ar#ument +hen startin# the domain%s Administration
<erver
0D+eblo#ic./roduction5ode-nabledTtrue /roduction mode is set for all >ebHo#ic <erver instances in a
#iven domain.
>7.I downloaded the Web#o/ic "erver installation file$ but the installation pro/ra* will not
run. What should I do?
3he installation file may have been corrupted durin# the do+nload. 1un a chec"sum on the installation
file and chec" +ith technical support for the proper values.
>9.,o I need to install Web#o/ic "erver as root on "olaris?
9o you don%t need to be root, dependin# on directory permissions.
>;.Can I run the Confi/uration Wi=ard outside the installer?
Ces. Cou can start the .onfi#uration >iFard from the <tart menu or usin# a script in the utils
directory. <ee .reatin# Domains and <ervers in .onfi#urin# and 5ana#in# >ebHo#ic <erver.
><.Cow do I edit the confi/.x*l file?
3he persistent confi#uration for a domain of >ebHo#ic <ervers and clusters is stored in an ^5H
confi#uration file !confi#.xml$. Cou can modify this file in the follo+in# +ays
4se the Administration .onsole. <ee =4sin# the Administration .onsole= in the Administration
.onsole 'nline 2elp.
If you +ant to create scripts that automate domain mana#ement, use the +eblo#ic.Admin
utility. <ee =+eblo#ic.Admin .ommand0Hine 1eference= in the .
If you +ant to create *ava0based mana#ement applications, use the *ava 5ana#ement
-xtensions !*5^$ Application/ro#rammin# Interface !A/I$. <ee the /ro#rammin# >ebHo#ic
5ana#ement <ervices +ith *5^ #uide.
If you +ant to edit the confi#.xml file directly !not recommended$, see the ?-A >ebHo#ic
<erver .onfi#uration 1eference.
>>.What is the free pool?
3he free pool is a data structure the -*? container uses to cache anonymous instances of a #iven bean
type. 3he free pool improves performance by reusin# ob(ects and s"ippin# container callbac"s +hen it
can.
1@@.Can I use the (oint-ase ,-)" included with Web#o/ic "erver for develop*ent or
production?
/oint?ase <erver is an all0*ava D?5< product included in the >ebHo#ic <erver distribution solely in
support of >ebHo#ic <erver evaluation, either in the form of custom trial applications or throu#h
pac"a#ed sample applications provided +ith >ebHo#ic <erver. 9on0evaluation development and7or
production use of the /oint?ase <erver re)uires a separate license be obtained by the end user
directly from /oint?ase.
1@1.Cow can I enable %racle Advanced "ecurit+ encr+ption on the 6,-C %racle Ihin driver
with a Web#o/ic 6,-C Connection (ool?
'racle Advanced <ecurity encryption relies on features available throu#h connection properties in the
*D?. driver from 'racle. Cou can specify connection properties in a >ebHo#ic *D?. connection pool in
the /roperties attribute. 3his attribute is available on the *D?. .onnection /ool cM .onfi#uration cM
Oeneral tab in the Administration .onsole. >hen >ebHo#ic <erver createsdatabase connections for the
connection pool, it passes the properties to the *D?. driver so that connections are created +ith the
specified properties.
Bor example, to enable 'racle Advanced <ecurity encryption, you may +ant to specify the
follo+in# options
/roperties userT<.'33
oracle.net.encryptionXclientTA..-/3-D
oracle.net.encryptionXtypesXclientT1.4X256
oracle.net.cryptoXchec"sumXclientTA..-/3-D
protocolTthin
9ote <ee the 'racle documentation for details about re)uired properties for 'racle
Advanced <ecurity encryption. /roperties listed above are for illustration only.
3he resultin# entry in the confi#.xml file +ould loo" li"e
\*D?..onnection/ool
Driver9ameT=oracle.(dbc.driver.'racleDriver=
9ameT=oracle/ool=
/ass+ordT=63D-<;1e9n&"COUL+T=
/ropertiesT=userT<.'33:
oracle.net.encryptionXclientTA..-/3-D:
oracle.net.encryptionXtypesXclientT1.4X256: oracle.net.cryptoXchec"sumXclientTA..-/3-D:
protocolTthin=
41HT=(dbcoraclethinaserverportsid=7M
9ote Hine brea"s added for readability.
1@2.When should I use a Ix,ata"ource instead of a ,ata"ource?
>hen you select 2onor Olobal 3ransactions in the Administration .onsole, you create a
*D?.3xData<ource in the confi#.xml file !the default$. If you clear the 2onor Olobal 3ransactions
chec" box, you create a *D?.Data<ource in the confi#.xml file. <ee =>hen to -nable Olobal
3ransactions in a Data <ource= in the Administration .onsole 'nline 2elp.
1@0.Can I enable reDuests to a 6,-C connection pool for a database connection to wait until
a connection is available?
Ces. Cou can set t+o *D?. connection pool properties to enable connection re)uests to +ait for a
connection
.onnection1eserve3imeout<econds
2i#hest9um>aiters
1@3.What happens when *+ database is restarted or beco*es unreachable? ,oes *+
connection pool stick around?
Ces. 3he pool is independent of its ability to communicate +ith to the D?5<. All connections in the
connection pool may become defunct, but the connection pool still exists. Cou can confi#ure the
connection pool so that >ebHo#ic <erver tests the connections in the pool and replaces bad
connections +hen it can.
3o manually restart the connection pool usin# the Administration .onsole after a database failure, you
can undeploy the connection pool by removin# all of its deployment tar#ets, and then redeploy the
connection pool by addin# deployment tar#ets.
3o do this from the command line usin# =+eblo#ic.Admin=, set the =3ar#ets= attribute of the pool to an
empty strin# !==$ and then set it to the desired set of tar#ets.
1@7.When should I use )ulti(ools?
Cou can use 5ulti/ools in one of t+o +ays
1$ Bor hi#h availability in the event a database connection fails, or
2$ Bor load balancin# bet+een *D?. connection pools. ?ecause you can choose only one option, you
need to determine the primary purpose of your 5ulti/ool.
9ote If you implement 5ultipools for a *D?. application, do not confi#ure driver0level load balancin#
or failover for the connection pools used by the 5ulti/oolcthe 5ulti/ool provides the same
functionality as confi#urin# driver0level load balancin# or failover.
1@9.What is 6,-C?
*D?. is an A/I for accessin# databases in a uniform +ay.
*D?. provides
o /latform0independent access to databases
o Hocation transparency
o 3ransparency to proprietary database issues
o <upport for both t+o0tier and multitier models for database access
3he *ava Database .onnectivity !*D?.$ specification
o Is a platform0 and vendor0independent mechanism for accessin# and updatin# a
database
o /rovides transparency from proprietary vendor issues
o 1e)uires the use of a driver
*D?. drivers are supplied by >H< or your database vendor.
1@;.What is the use of ,ata "ource in Weblo/ic?
Data sources
o Allo+ database connectivity to be mana#ed by the application server
o 4se a dynamic pool of reusable database connections
o Are obtained by applications from the serverAs *9DI tree
1@<.What is the scope of the ,ata "ource in Weblo/ic server?
o -ach data source confi#uration or Zmodule[ is persisted as a separate ^5H document .
o 3he system modules that are created +ith the console or >H<3 are
<tored in the domain%s confi#7*dbc directory
Available to all applications in the domain
o Application0specific modules are
Deployed as part of *ava -- enterprise applications
Accessible only by the containin# application
1@>.#ist default Weblo/ic provided 6,-C ,rivers?
o 'racle and third0party drivers are included in >H< installation for many popular
database products
'racle Ki, 1Jg, and 11g
<ybase Adaptive <erver
5icrosoft <EH <erver
I?5 D?2
Informix
5y<EH
/oint?ase
o ?y default, these drivers are added to serverAs classpath.
11@.What is a ,ata "ource?
o A data source ob(ect provides a +ay for a *D?. client to obtain a database connection
from a connection pool.
o A data source
Is stored in the 'racle >ebHo#ic <erver *9DI tree
.an support transactions
Is associated +ith a connection pool
111.What is a Connection (ool?
o A connection pool is a #roup of ready0to0use database connections associated +ith a
data source.
o .onnection pools
Are created at 'racle >ebHo#ic <erver startup
.an be administered usin# the Administration .onsole
.an be dynamically resiFed to accommodate increasin# load
112.What are the benefits of havin/ ,ata "ources and Connection (ools in Weblo/ic?
o 3he follo+in# are some advanta#es of this approach
3ime and overhead are saved by usin# an existin# database connection.
.onnection information is mana#ed in one location in the Administration
.onsole.
3he number of connections to a database can be controlled.
3he D?5< can be chan#ed +ithout the application developer havin# to modify
the underlyin# code.
A connection pool allo+s an application to Zborro+[ a D?5< connection
110.Cow ,ata "ources are used in Weblo/ic?
A client retrieves a data source throu#h a *9DI loo"up and uses it to obtain a database connection.
113.What is )ulti ,ata "ources?
o 5ulti data source
Is an abstraction around a #roup of data sources
Determines +hich data source to use to satisfy the re)uest dependin# on the
al#orithm selected in the multi data source confi#uration
Hoad balancin# or failover
Is bound to the *9DI tree
o ^A support for multi data sources
3he >H< *D?. supports usin# multi data sources in ^A transactions.
Cou can confi#ure the data sources contained +ithin the multi data source to
use ^A *D?. drivers.
117.What is the functionalit+ of P)essa/eJ%riented )iddlewareQ?
5essa#e0oriented middle+are refers to an infrastructure that supports messa#in#.
3ypical messa#e0oriented middle+are architectures define the follo+in# elements
5essa#e structure
3he +ay to send and receive messa#es
<calin# #uidelines
119.!xplain about (ointJtoJ(oint 1Queue2?
5any producers can serialiFe messa#es to multiple receivers in a )ueue.
11;.!xplain about (ublishJ"ubscribe 1Iopics2?
/ublishin# and subscribin# to a topic decouples producers from consumers.
11<.!xplain about %racle Web#o/ic "erver 6)" Geatures?
'racle >ebHo#ic <erver *5< supports
o /3/ and pub7sub domains
o Ouaranteed and transactional messa#e delivery
o Durable subscribers
o Distributed destinations
o 1ecovery from failed servers
11>.Cow will +ou i*ple*ent P)essa/in/ "erviceQ in Weblo/ic?
o In 'racle >eblo#ic <erver, the messa#in# service is implemented throu#h a *5<
server.
o A *5< server receives and distributes messa#es.
12@.What is the user of PConnection GactoriesQ in 6)"?
o *5< connection factories are used to set default client connection parameters,
includin#
5essa#e priority
5essa#e time0to0live !33H$
5essa#e persistence
3ransactional behavior
Ac"no+led#ement policy
Blo+ control
o >H< provides a default client connection factory that
4ses >ebHo#icAs default connection settin#s
Is located on the server *9DI tree at +eblo#ic.(ms..onnectoryBactory
121.What is the use of P,estinationQ in 6)"? Cow *an+ t+pes of P,estinationsQ are
available in 6)"?
o A destination is a li#ht+ei#ht ob(ect that is stored in *9DI.
o It is the tar#et on a *5< server for sendin# or receivin# messa#es.
o 3he *5< destination types are
Eueue
3opic
122.!xplain about PQueue ,estinationsQ?
In *5< point0to0point messa#in#, note the follo+in#
o .lients communicate +ith a 0ueue destination.
o 5essa#es are distributed to consumers in a serial fashion !first in, first out$.
o -ach messa#e is delivered only to a sin#le consumer.
120.!xplain about PIopic ,estinationsQ?
In *5< publish7subscribe messa#in#, the follo+in# is true
o .lients communicate +ith a topic destination.
o 5essa#es are broadcast to all subscribers.
o A messa#e can be saved until at least one subscriber has consumed it !Zdurable[$.
123.!xplain about Ihreshold and Quotas in 6)"?
o A threshold and a )uota can be set for the server and destination ob(ects.
o A )uota is a limit defined for the *5<0administered ob(ects: it includes the follo+in#
values
3he maximum number of bytes that can be stored
3he maximum number of messa#es that can be stored
o A threshold is a limit that tri##ers messa#e pa#in#, flo+ control, and lo##ed +arnin#s,
usin#
4pper and lo+er values for the number of bytes
4pper and lo+er values for the number of messa#es
127.,ifference between P,urable "ubscribers and "ubscriptionsQ?
o Durable subscribers re#ister durable subscriptions for #uaranteed messa#e delivery
even if the subscribers are inactive.
o A subscriber is considered active if the *ava ob(ect that represents it exists.
o ?y default, subscribers are nondurable.
o Administrators confi#ure
>here the messa#es are persisted
/ersistent connection factories and destinations
129.What is P(ersistent )essa/in/Q? When to &se it?
o /ersistent messa#in# permits messa#es in memory to be +ritten out to a persistent
store.
o .onfi#ure persistent messa#in# if
Development re)uires durable subscriptions !use durable subscribers in
the application$
Cou re)uire that in0pro#ress messa#es persist across server restarts
12;.Cow will +ou Confi/urin/ a ,urable "ubscription in Weblo/ic?
o 3o confi#ure durable subscriptions, an administrator must
.reate and confi#ure a *5< store
.onfi#ure connection factories or destinations as persistent
Associate the *5< store +ith the *5< server
o 3he *5< store can be confi#ured to use either
A file store
A *D?. store !a connection pool$
12<.Cow a ,urable "ubscription Works?
o If a subscriber client is active, messa#es are delivered normally.
o >hen the client becomes active a#ain, its ID is used to retrieve and redeliver
messa#es.
12>.What 'ode *ana/er can do in Weblo/ic server?
Cou can use 9ode 5ana#er to
<tart, shut do+n, and restart an Administration <erver
<tart, shut do+n, suspend, and restart 5ana#ed <ervers
Automatically restart the Administration and 5ana#ed <ervers on failure
5onitor servers and collect lo# data
10@.,oes the Web#o/ic 6)" server find out about closed or lost connections$
crashes$ and other proble*s and does it recover fro* the*?
Ces, but ho+ it does this depends on +hether a *ava client crashes or >ebHo#ic <erver crashes, as
follo+s
If a *ava client crashes then the *5< server +ill clean up all the outstandin# server0side
resource from the crashed client *L5, such as
*5< connection!s$ from the crashed client *L5
*5< temporary destination!s$ created under the above *5< connection!s$
*5< session!s$ created under the above *5< connection!s$
*5< client!s$ created under the above *5< session!s$ !connection consumer and re#ular
consumer$
*5< bro+ser!s$ created under the above session!s$
*5< producer!s$ created under the above session!s$
If >ebHo#ic <erver crashes and it is the front0end to the *5< server, then
A *5< client +ill lose all the server0side resources listed above.
3he client%s (avax.(ms.-xceptionHistener.on-xception!...$ +ill be called !if
(avax.(ms.*5<.onnection.set-xceptionHistener is set$ +ith a
Host<erver-xception, +hich extends *5<-xception.
If >ebHo#ic server crashes and it is a bac"0end to the *5< server, then
A *5< client may partially lose some of the server0side resources listed above !only the
resource on the crashed server, such as *5< temporary destination!s$, *5< client!s$ and *5<
bro+ser!s$.
3he client%s (avax.(ms.-xceptionHistener.on-xception!...$ +ill be called !if
+eblo#ic.(ms.extensions.>H<ession.set-xceptionHistener is set$ +ith a
.onsumer.losed-xception, +hich extends *5<-xception.
101.What Is the 6ava )essa/e "ervice?
An enterprise messa#in# system enables applications to communicate +ith one another throu#h the
exchan#e of messa#es. A messa#e is a re)uest, report, and7or event that contains information needed
to coordinate communication bet+een differentapplications. A messa#e provides a level of abstraction,
allo+in# you to separate the details about the destination system from the application code.
3he *ava 5essa#e <ervice !*5<$ is a standard A/I for accessin# enterprise messa#in# systems.
<pecifically, *5<
-nables *ava applications sharin# a messa#in# system to exchan#e messa#es
<implifies application development by providin# a standard interface for creatin#, sendin#, and
receivin# messa#es
102.Cow *an+ )essa/in/ )odules are available in Weblo/ic?
*5< supports t+o messa#in# models point0to0point !/3/$ and publish7subscribe !pub7sub$. 3he
messa#in# models are very similar, except for the follo+in# differences
/3/ messa#in# model enables the delivery of a messa#e to exactly one recipient.
/ub7sub messa#in# model enables the delivery of a messa#e to multiple recipients.
100.!xplain about (ointJtoJ(oint )essa/in/?
3he point0to0point !/3/$ messa#in# model enables one application to send a messa#e to another. /3/
messa#in# applicationssend and receive messa#es usin# named )ueues. A )ueue sender !producer$
sends a messa#e to a specific )ueue. A )ueue receiver !consumer$ receives messa#es from a specific
)ueue.
103.!xplain about (ublishB"ubscribe )essa/in/?
3he publish7subscribe !pub7sub$ messa#in# model enables an application to send a messa#e to
multiple applications. /ub7sub messa#in# applications send and receive messa#es by subscribin# to a
topic. A topic publisher !producer$ sends messa#es to a specific topic. A topic subscriber !consumer$
retrieves messa#es from a specific topic.
107.!xplain about )essa/e (ersistence?
As per the Z5essa#e Delivery 5ode[ section of the *5< <pecification, messa#es can be specified as
persistent or non0persistent
A persistent *essa/e is #uaranteed to be delivered once0and0only0once. 3he messa#e
cannot be lost due to a *5< provider failure and it must not be delivered t+ice. It is not
considered sent until it has been safely +ritten to a file or database. >ebHo#ic *5< +rites
persistent messa#es to a >ebHo#ic persistent store !dis"0base file or *D?.0accessible
database$ that is optionally tar#eted by each *5< server durin# confi#uration.
'onJpersistent *essa/es are not stored. 3hey are #uaranteed to be delivered at0most0
once, unless there is a *5< provider failure, in +hich case messa#es may be lost, and must
not be delivered t+ice. If a connection is closed or recovered, all non0persistent messa#es that
have not yet been ac"no+led#ed +ill be redelivered. 'nce a non0persistent messa#e is
ac"no+led#ed, it +ill not be redelivered.
109.Iopics vs. Queues?
<urprisin#ly, +hen you are startin# to desi#n your application, it is not al+ays immediately obvious
+hether it +ould be better to use a 3opic or Eueue. In #eneral, you should choose a 3opic only if one
of the follo+in# conditions applies
3he same messa#e must be replicated to multiple consumers.
A messa#e should be dropped if there are no active consumers that +ould select it.
3here are many subscribers, each +ith a uni)ue selector.
It is interestin# to note that a topic +ith a sin#le durable subscriber is semantically similar to a )ueue.
3he differences are as follo+s
If you chan#e a topic selector for a durable subscriber, all previous messa#es in the
subscription are deleted, +hile if you chan#e a )ueue selector for consumer, no messa#es in
the )ueue are deleted.
A )ueue may have multiple consumers, and +ill distribute its messa#es in a round0
robin fashion, +hereas a topic subscriber is limited to only one consumer.
10;.As+nchronous vs. "+nchronous Consu*ers?
In #eneral, asynchronous !on5essa#e$ consumers perform and scale better
than synchronous consumers
Asynchronous consumers create less net+or" traffic. 5essa#es are pushed unidirectionally,
and are pipelined to the messa#e listener. /ipelinin# supports the a##re#ation of multiple
messa#es into a sin#le net+or" call.
'ote In >ebHo#ic <erver, your synchronous consumers can also use the same efficient behavior as
asynchronous consumers by enablin# the /refetch 5ode for <ynchronous .onsumers option on *5<
connection factories
Asynchronous consumers use fe+er threads. An asynchronous consumer does not use a
thread +hile it is inactive. Asynchronous consumer consumes a thread for the duration of its
receive call. As a result, a thread can remain idle for lon# periods, especially if the call
specifies a bloc"in# timeout.
Bor application code that runs on a server, it is almost al+ays best to use asynchronous
consumers, typically via 5D?s. 3he use of asynchronous consumers prevents
the application code from doin# a bloc"in# operation on the server. A bloc"in# operation, in
turn, idles a server0side thread: it can even cause deadloc"s. Deadloc"s occur +hen bloc"in#
operations consume all threads. >hen no threads remain to handle the operations
re)uired unbloc"in# the bloc"in# operation itself, that operation never stops bloc"in#.
10<.What is a ,istributed ,estination?
A distributed destination is a set of destinations !)ueues or topics$ that are accessible as a sin#le,
lo#ical destination to a client. A distributed destination has the follo+in# characteristics
It is referenced by its o+n *9DI name.
5embers of the set are usually distributed across multiple servers +ithin a cluster, +ith each
destination member belon#in# to a separate *5< server.
10>.Wh+ &se a ,istributed ,estination?
Applications that use distributed destinations are more hi#hly available than applications that use
simple destinations because >ebHo#ic *5< provides load balancin# and failover for member
destinations of a distributed destination +ithin a cluster. 'nce properly confi#ured, your producers and
consumers are able to send and receive messa#es throu#h the distributed destination. >ebHo#ic *5<
then balances the messa#in# load across all available members of the distributed destination. >hen
one member becomes unavailable due a server failure, traffic is then redirected to+ard other available
destination members in the set.
13@.Cow *an+ I+pes of ,istributed ,estinations are available?
4niform Distributed Destinations
>ei#hted Distributed Destinations
&nifor* ,istributed ,estinations
In a uniform distributed destination !4DD$, each of the member destinations has a consistent
confi#uration of all distributed destination parameters, particularly in re#ards to +ei#htin#, security,
persistence, pa#in#, and )uotas.
'racle recommends usin# 4DDs because you no lon#er need to create or desi#nate destination
members, but instead rely on >ebHo#ic <erver to uniformly create the necessary members on the *5<
servers to +hich a 4DD is tar#eted. 3his feature of 4DDs provides dynamic updatin# of a 4DD +hen a
ne+ member is added or a member is removed.
Wei/hted ,istributed ,estinations
In a +ei#hted distributed destination, the member destinations do not have a consistent confi#uration
of all distributed destination parameters, particularly in re#ards to +ei#htin#, security, persistence,
pa#in#, and )uotas.
'racle recommends convertin# +ei#hted distributed destinations to 4DDs because of the
administrative inflexibility +hen creatin# members that are intended to carry extra messa#e load or
have extra capacity !more +ei#ht$. Hac" of a consistent member confi#uration can lead to unforeseen
administrative and application problems because the +ei#hted distributed destination cannot be
deployed consistently across a cluster.
131.What is 6',I?
*9DI !*ava 9amin# and Directory Interface$ is a *ava -- loo"up service that maps names to services
and resources. *9DI provides a directory of advertised resources that exist on a particular stand0alone
!unclustered$ >ebHo#ic server, or +ithin a >ebHo#ic server cluster . -xamples of such resources
include *5< connection factories, *5< destinations, *D?. !database$ data sources,
and application -*?s.
A client connectin# to any >ebHo#ic server in a >ebHo#ic cluster can transparently reference any *9DI
advertised service orresource hosted on any >ebHo#ic server +ithin the cluster. 3he client doesn%t
re)uire explicit "no+led#e of +hich particular >ebHo#ic server in the cluster hosts a desired resource.
132.What is a 6)" connection factor+?
A *5< connection factory is a named entity resource stored in *9DI. Applications, messa#e driven
beans !5D?s$, and messa#in# brid#es loo"up a *5< connection factory in *9DI and use it to create
*5< connections. *5< connections are used in turn to create *5< sessions, producers, and consumers
that can send or receive messa#es.
130.What is a 6)" connectionJid?
*5< connection0ids are used to name *5< client connections. Durable subscribers re)uire named
connections, other+ise connections are typically unnamed. 9ote that +ithin a clustered set of servers
or stand0alone server, only one *5< client connection may use a particular named connection at a
time. An attempt to create ne+ connection +ith the same name as an existin# connection +ill fail.
133.What is the difference between a 6)" topic and a 6)" Dueue?
*5< )ueues deliver a messa#e to one consumer, +hile *5< topics deliver a copy of each messa#e to
each consumer.
137.What is a nonJdurable topic subscriber?
A non0durable subscriber creates unnamed subscriptions that exist only for the life of the *5< client.
5essa#es in a non0durable subscription are never persistedceven +hen the messa#e%s publisher
specifies a persistent )uality of service !E'<$. <huttin# do+n a *5< server terminates all non0durable
subscriptions.
139.What is a durable subscriber?
A durable subscriber creates named subscriptions that continue to exist even after the durable
subscriber exits or the server reboots. A durable subscriber connects to its subscription by specifyin#
topic0name, connection0id, and subscriber0id. 3o#ether, the connection0id and subscriber0id uni)uely
name the subscriberAs subscription +ithin a cluster. A copy of each persistent messa#e published to a
topic is persisted to each of the topic%s durable subscriptions. In the event of a server crash and
restart, durable subscriptions and their unconsumed persistent messa#es are recovered.
13;.What is the Web#o/ic "toreJandJGorward "ervice?
3he >ebHo#ic <tore0and0Bor+ard !<AB$ <ervice enables >ebHo#ic <erver to deliver messa#es reliably
bet+een applications that are distributed across >ebHo#ic <erver instances. Bor example, +ith the
<AB service, an application that runs on or connects to a local >ebHo#ic <erver instance can
reliably send messa#es to a destination that resides on a remote server. If the destination is not
available at the moment the messa#es are sent, either because of net+or" problems or system
failures, then the messa#es are saved on a local server instance, and are for+arded to the remote
destination once it becomes available.
13<.When should I use the Web#o/ic "toreJandJGorward "ervice?
3he >ebHo#ic <tore0and0Bor+ard !<AB$ <ervice should be used +hen for+ardin# *5< messa#es
bet+een >ebHo#ic <erver K.J or later domains. 3he <AB service can deliver messa#es
?et+een t+o stand0alone server instances.
?et+een server instances in a cluster.
Across t+o clusters in a domain.
Across separate domains.
13>.What is a *essa/in/ brid/e?
5essa#in# brid#es are administratively confi#ured services that run on a >ebHo#ic server. 3hey
automatically for+ard messa#es from a confi#ured source *5< destination to a confi#ured tar#et *5<
destination. 3hese destinations can be on different servers than the brid#e and can even be forei#n
!non0>ebHo#ic$ destinations. -ach brid#e destination is confi#ured usin# the four common properties
of a remote provider
3he initial context factory.
3he connection 41H.
3he connection factory *9DI name.
3he destination *9DI name.
5essa#in# brid#es can be confi#ured to use transactions to ensure exactly0once messa#e for+ardin#
from any ^A capable !#lobal transaction capable$ *5< provider to another.
17@.When should I use a *essa/in/ brid/e?
3ypically, messa#in# brid#es are used to provide store0and0for+ard hi#h availability desi#n
re)uirements. A messa#in# brid#e is confi#ured to consume from a sender%s local destination and
for+ard it to the sender%s actual tar#et remote destination. 3his provides hi#h availability because the
sender is still able to send messa#es to its local destination even +hen the tar#et remote destination
is unreachable. >hen a remote destination is not reachable, the local destination automatically be#ins
to store messa#es until the brid#e is able to for+ard them to the tar#et destination +hen the tar#et
becomes available a#ain.
171.When should I avoid usin/ a *essa/in/ brid/e?
'ther methods are preferred in the follo+in# situations
1eceivin# from a remote destinationcuse a messa#e driven -*? or implement a client
consumer directly.
<endin# messa#es to a local destinationcsend directly to the local destination.
-nvironment +ith lo+ tolerance for messa#e latency. 5essa#in# ?rid#es increase latency and
may lo+er throu#hput. 5essa#in# brid#es increase latency for messa#es as they introduce an
extra destination in the messa#e path and may lo+er throu#hput because they for+ard
messa#es usin# a sin#le thread.
Bor+ard messa#es bet+een >ebHo#ic K.J domainsc4se >ebHo#ic <tore0and0Bor+ard.
172.Cow *an+ t+pes of 6)" stores are available?
o 3he *5< store can be confi#ured to use either
A file store
A *D?. store !a connection pool$
170.Cow will +ou confi/ure a 6)" 6,-C "tore?
o 3o confi#ure *5< *D?. persistence, perform the follo+in#
.reate a *D?. Data<ource.
.reate a *5< store and refer to the *D?. Data<ource.
1efer to the *5< store from the *5< server confi#uration.
o 3he re)uired infrastructure !tables and so on$ is created automatically.
173.What Is a Iransaction?
o A transaction is a mechanism to handle #roups of operations as thou#h they +ere one.
o -ither all operations in a transaction occur or none occur
at all.
o 3he operations involved in a transaction mi#ht rely on multiple servers and databases.
177.Cow *an+ I+pes of Iransactions are there? !xplain?
o A local transaction deals +ith a sin#le resource mana#er. Hocal transactions use the
non0-xtended Architecture !non0^A$ interface bet+een 'racle >ebHo#ic <erver and
the resource mana#er.
o A distributed transaction coordinates or spans multiple resource mana#ers.
o Olobal transactions can deal +ith multiple resource mana#ers. Olobal transactions use
the -xtended Architecture !^A$ interface bet+een 'racle >ebHo#ic <erver and the
resource mana#ers.
Cou need to create non0^A or ^A resources for local transactions. 2o+ever, for
#lobal transactions, you need to create only ^A resources.
179.!xplain about IwoJ(hase Co**it (rotocol?
o 3he 3+o0/hase .ommit !2/.$ protocol uses t+o steps to commit chan#es +ithin a
distributed transaction.
/hase 1 as"s the 15s to prepare to ma"e the chan#es.
/hase 2 as"s the 15s to commit and ma"e the chan#es permanent or
to roll bac" the entire transaction.
o A #lobal transaction ID !^ID$ is used to trac" all the chan#es associated +ith a
distributed transaction.
17;.!xplain about !xtended Architecture (rotocol 1MA2?
3he -xtended Architecture !^A$ protocol
o Is the interface that is used bet+een >H< and the 15s
o Implements the 2/. protocol
o Allo+s pro#rams to control the 15s that are involved in distributed transactions
17<.What is the user of PIransaction #o/Q?
o -ach server has a transaction lo# that stores information about committed
transactions coordinated by the server that may not have been completed.
'racle >ebHo#ic <erver uses the transaction lo# +hen recoverin# from system
crashes or net+or" failures.
Cou cannot directly vie+ the transaction lo# because the records are in a binary format and
are stored in the default persistent store for the server.
17>.!xplain about #o//in/ #ast :esource?
o Cou can confi#ure a *D?. data source to enable the Ho##in# Hast 1esource !HH1$
transaction optimiFation, +hich
-nables one non0^A resource to participate in a #lobal transaction
2as improved performance and the same A.ID #uarantee as ^A
o 3he HH1 optimiFation improves performance by
1emovin# the need for an ^A *D?. driver to connect to the database. ^A *D?.
drivers are typically inefficient compared to non0^A *D?. drivers.
1educin# the number of processin# steps to complete the transaction, +hich
also reduces net+or" traffic and I7'
1emovin# the need for ^A processin# at the database level !if the database is
the one non0^A resource$
19@.What Is #,A(?
3he Hi#ht+ei#ht Directory Access /rotocol
o Is derived from ^.5JJ
o /rovides a hierarchical loo"up service
o <upports sophisticated searchin#
o .an be secured via <<H
191.!xplain "ecurit+ :eal*s?
o A security realm is a collection of system resources and security service providers.
o 'nly one security realm can be active at a #iven time.
o A sin#le security policy is used in any realm.
o 4sers must be reco#niFed by an authentication provider of the security realm.
o Administration tas"s include creatin# security realms.
192.What Is ""#?
<ecure <oc"ets Hayer !<<H$ is a protocol that enables
o .onnection security throu#h encryption
o A server to authenticate to a client
o A client to authenticate to a server !optional$
o Data inte#rity such that the data that flo+s bet+een a client and server is protected
from tamperin# by a third party
163.>hat Is a Deployment /lanG
It is an optional ^5H document that resides outside an application archive.
It confi#ures an application for deployment to a specific >H< environment.
It is created and o+ned by administrators or developers for a particular
environment.
A *ava-- deployment plan
Is an ^5H file that is associated +ith an application
1esides outside an application archive
<ets or overrides the values in the *ava-- deployment descriptors
Allo+s a sin#le application to be easily customiFed to multiple deployment environments
164.What are the Advanta/es of (roduction :edeplo+*ent?
<aves the trouble of
<chedulin# application do+ntime
<ettin# up redundant servers to host ne+ application versions
5ana#in# client access to multiple application versions manually
1etirin# older versions of an application manually
!xplain about (acka/in/ Applications?
>hen you deploy applications to a sin#le 5ana#ed <erver, you can
deploy the applications in an exploded format.
'racle recommends deployin# pac"a#ed applications to a cluster of
5ana#ed <ervers as .+ar, .ear, or .(ar file
197.What are the %racle Web#o/ic "erver ""# :eDuire*ents?
3o enable 'racle >ebHo#ic <erver <<H, you must
'btain an appropriate di#ital certificate
Install the certificate
.onfi#ure <<H properties
.onfi#ure t+o0+ay authentication !if desired$
<<H impacts performance.
199.What is the user of ke+tool &tilit+ in W#"?
"eytool is a standard *2<- <DI utility for mana#in#
3he #eneration of private "eys and the correspondin# di#ital
certificates
Ieystores !databases$ of private "eys and the associated
certificates
3he "eytool utility can the display certificate and "eystore contents.
19;.Cow W#" (rotectin/ A/ainst Attacks? What kinds of Attacks are there?
>H< can help protect applications a#ainst several attac"s
5an0in0the0middle attac"s
Denial of service !Do<$ attac"s
Har#e buffer attac"s
.onnection starvation attac"s
3he slides that follo+ detail the countermeasures that >H< provides to
address these attac"s.
19<.!xplain about )anJinJtheJ)iddle Attacks?
In the Zman0in0the0middle[ attac", a third party poses as a destination
host interceptin# messa#es bet+een the client and the real host.
Instead of issuin# the real destination hostAs <<H certificate, the
attac"er issues his or her o+n hopin# that the client +ould accept it as
bein# from the real destination host.
3he Zman0in0the0middle[ attac"s can be resisted by usin#
a 2ost 9ame Lerifier.
A 2ost 9ame Lerifier validates that the host to +hich an <<H
connection is made is the intended or authoriFed party.
>H< provides a 2ost 9ame Lerifier by default.
A custom 2ost 9ame Lerifier can be created by implementin#
the interface+eblo#ic.security.<<H.2ostnameLerifier
19>.!xplain about ,enial of "ervice Attacks 1,%"2?
Do< attac"s are attempts by attac"ers to prevent le#itimate users of a
service from usin# that service.
3here are three basic types of attac"
.onsumption of scarce, limited, or nonrene+able resources
Destruction or alteration of confi#uration information
/hysical destruction or alteration of net+or" components
2arden >H< a#ainst Zdenial of service[ attac"s by
Bilterin# incomin# net+or" connections
.onfi#urin# consumable >H< resources +ith the appropriate threshold
and )uotas
Himitin# access to confi#uration information and bac"in# up
confi#uration files
/reventin# unauthoriFed access by protectin# pass+ords a#ainst
pass+ord0#uessin# attac"s
1;@.!xplain about Gilterin/ 'etwork Connections?
>H< can be confi#ured to accept or deny net+or" connections based
on the ori#in of the client.
3his feature can be used to
1estrict the location from +hich connections to >H< are made
1estrict the type of connection made, that is, allo+ only <<H
connections and re(ect all others
3o filter net+or" connections, create a class that implements the
.onnectionBilter interface and install it usin# the Administration
.onsole.
1;1.!xplain about #ar/e -uffer Attacks?
o Individuals can try to brin# do+n a >eb site by sendin# a lar#e buffer of data, +hich
starves the system of memory.
o Administrators can combat this attac" by settin# a threshold for incomin# data.
1;2.!xplain about Connection "tarvation?
o Individuals can try to ta"e do+n a >eb site by sendin# small, incomplete messa#es
that cause the server to +ait.
o Administrators can combat this attac" by settin# a threshold.
o .onnections time out +hile +aitin# for the remainder of the data if they have reached
the threshold set by the administrator.
1;0.!xplain about &ser #ockout?
o Individuals attempt to hac" into a computer usin# various combinations of usernames
and pass+ords.
o Administrators can protect a#ainst this security attac" by settin# the loc"out
attributes.
o 3he administrator can unloc" a loc"ed user usin# the console.
1;3.Cow will +ou (rotectin/ the Ad*inistration Console?
o Cou can confi#ure a separate administration port for all administration traffic.
o Cou can chan#e the .ontext path of the console.
o Cou can disable the console !application$.
1;7.What are the advanta/es of ,eplo+*ent (lan?
o >or"s by settin# or overridin# the deployment property values that are defined in an
applicationAs >H< deployment descriptor
o 2elps to easily modify an applicationAs >H< confi#uration for deployment into different
multiple >H< environments +ithout modifyin# the deployment descriptor files that are
included in the application archive
-nables an application to be deployed to multiple domains or to multiple tar#et servers
and clusters that have a different confi#uration +ithin the same
1. domain
1;9.What is the user of weblo/ic.(lan?enerator?
1. Is a *ava0based deployment confi#uration tool
2. Is primarily intended for developers +ho +ant to export portions of an 'racle
>ebHo#ic <erver deployment confi#uration into an ^5H deployment plan
3. -nables you to #enerate a basic 'racle >ebHo#ic <erver confi#uration for applications
that have only *2--deployment descriptors
1;;.Cow will +ou /enerate a ,eplo+*ent (lan &sin/ the Ad*inistration Console?
1. 3he Administration .onsole automatically #enerates or updates the deployment plan.
2. Cou can #enerate a deployment plan usin# the Administration .onsole usin# the
follo+in# steps
/repare the deployment files.
Install the application archive.
<ave the confi#uration chan#es to a deployment plan.
1;<.Cow *an+ t+pes of "ta/ed ,eplo+*ent are available in W#"?
Cou can confi#ure deployment per server or for each application as
1. sta/ed !default$ Biles are copied to the preconfi#ured sta#in# directory for
preparation and activation.
2. nosta/e Biles are deployed from a static location.
3. externalTsta/e Biles are copied by a user or a third0party tool before deployment.
1;>.!xplain about (roduction :edeplo+*ent?
1. Cou can redeploy a revised version of a production application alon#side the older
version
>ithout affectin# the existin# clients to the application
>ithout interruptin# the availability of the application to the ne+ client re)uest
2. 'racle >ebHo#ic <erver automatically mana#es client connections so that
-xistin# clients continue to use the older application
9e+ client re)uests are directed to the ne+er application
3he older version is undeployed after all current clients complete their +or".
1<@.!xplain about Application Availabilit+$ after deplo+in/Binstall to W#"?
1. ?y default, +hen an application is redeployed
It is unavailable to clients for a brief time
-xistin# clients lose any conversational state
2. <ome types of applications re)uire availability 24 hours a day, seven days a +ee".
3. 3hird0party proxy solutions are possible, but they re)uire multiple servers.
1<1.!xplain about Web#o/ic (roduction :edeplo+*ent?
1. /roduction redeployment
1. Allo+s t+o versions of a sin#le >eb application or module to run
simultaneously
2. 1e)uires you to include uni)ue version information either
>ithin the applicationAs 5-3A0I9B75A9IB-<3.5B file
As part of the deployment process
2. >hen a ne+ version is redeployed, >H< automatically
1outes existin# clients to the prior !retired$ version
1outes ne+ clients to the ne+ version
4ndeploys the prior version +hen all existin# clients finish their +or" or their
conversations time out
1<2.What are the :eDuire*ents and :estrictions for (roduction :edeplo+*ent in W#"?
1. /roduction redeployment is supported for
<tand0alone >eb Application !>A1$ modules and -nterprise Applications
!-A1s$ +hose client accesses the application via a >eb application !233/$
-nterprise Applications that are accessed by inbound *5< messa#es from a
#lobal *5< destination, or from inbound *.A re)uests
All types of >eb <ervices, includin# conversational and reliable >eb <ervices
2. /roduction redeployment is not supported for
<tand0alone -*? or 1esource Archive !1A1$ modules
Applications that use *3< drivers
Applications that obtain *D?. data sources via the Driver5ana#er A/I instead
of usin# the *9DI loo"up
Applications that include the -*? 1.1 container0mana#ed persistence !.5/$
-*?s
3. A deployed application must specify a version number.
4. >H< can host a maximum of t+o different versions of an application at one time.
5. >hen you are redeployin# a ne+ version of an application, the follo+in# features
cannot chan#e
Deployment tar#ets
<ecurity model
/ersistent store settin#s
1<0.:edeplo+in/ 8ersus ,istributin/ an applications in W#"?
1. Distributin# is an alternative to deployin# an application.
Distributin# an application prepares it for deployment by copyin# its files to all
tar#et servers and validatin# the files.
Cou can start a distributed application in Administration mode. Access to the
application is then restricted to a confi#ured Administration channel.
2. Distributin# a ne+ version of the application ma"es it available for testin# before bein#
released for #eneral consumption.
3. 1edeployin# a ne+ version of an application places the application immediately into
use and ma"es it available to ne+ client re)uests.
1<3.Cow will +ou ,istributin/ a 'ew Application 8ersion in W#"?
1. 4se the +eblo#ic.Deployer Vdistribute command.
2. After the application is distributed, start the application in Administration mode.
3. 3est the application.
4. >hen ready, start the application !+ithout usin# Vadminmode$.
5. 'ptionally set a retirement timeout for the older version of the application.
1<7.Cow will +ou Create )A'IG!"I.*f file for (roduction :edeplo+*ent?
1. .reate 5A9IB-<3.mf +ith the follo+in# contents
9ame (ava7util7
<pecification03itle *ava 4tility .lasses
<pecification0Lersion 1.2
<pecification0Lendor <un 5icrosystems, Inc.
Implementation03itle (ava.util
Implementation0Lersion build5&
Implementation0Lendor <un 5icrosystems, Inc.
2. 3hen add an entry for >H< versionin#
>eblo#ic0Application0Lersion Lersion1.J?eta
1<9.What is a cluster ,efinition?
1. A cluster is a #roup of 'racle >ebHo#ic <erver instances that +or" in coordination.
2. .lusterin# provides
2i#h availability
Hoad balancin#
<calability
1<;.What Is a Cluster?
A cluster
1. Is a lo#ical #roup of 'racle >ebHo#ic <ervers +ithin a domain
2. <upports features to
provide hi#h
availability for
>hole servers
>eb applications7services
-*? applications
*5<
3. Is transparent to a client
1<<.What are the -enefits of Clusterin/?
1. 3here are t+o main benefits of clusterin# to#ether 'racle >ebHo#ic <ervers
1. <calability
2. 2i#h availability
2. <calability is the ability to provide more capacity for an application, in this case, by
addin# additional servers +ithout havin# to ma"e ma(or architectural chan#es.
3. 2i#h availability ensures that +hen a server !in a cluster$ fails, there are other servers
to ta"e over the +or", so that the client is not affected.

1<>.What are the Fe+ Capabilities of clusterin/?
3he "ey capabilities of a >ebHo#ic cluster are
1. Application failover
>hen an ob(ect in an application that is performin# a tas" becomes
unavailable, another ob(ect ta"es over and finishes
the (ob.
2. <ite failover
>hen all the services and applications in a sin#le site fail, they can s+itch to a
separate site and continue processin#.
3. <erver mi#ration
>hen a server fails, pinned services can be mi#rated to another server in a
cluster.
4. Hoad balancin#
3as"s and communications are evenly distributed across multiple servers.
1>@.!xplain about Cluster Architecture?
1. Applications are #enerally bro"en into multiple tiers, each representin# its distinct
functionality
1. >eb tier
2. /resentation tier
3. ?usiness or ob(ect tier
2. >ebHo#ic provides clusterin# support for all three tiers.
3. 'ther services, such as *5< and *D?., can ta"e advanta#e of clusters but load0
balancin# and failover is a little different.
1>1.Cow the "erver will co**unicate in a Cluster?
3he 'racle >ebHo#ic <erver instances in a cluster communicate +ith one
another usin# t+o different techni)ues
4nicast7multicast !4D/$
<oc"ets !peer0to0peer 3./$
3he server instances use I/ unicast or multicast to broadcast the availability of
services and heartbeats that indicate continued availability.
I/ multicast broadcasts one0to0many communications
amon# clustered instances.
I/ unicast is an alternative to multicast to handle cluster messa#in# and
communications. 3he unicastconfi#uration is much easier because it does not
re)uire cross0net+or" confi#uration that multicast re)uires.
I/ soc"ets are used for peer0to0peer communications bet+een server
instances.
1>2.!xplain about Cluster Co**unication in W#"?
1. 5embers of a cluster cooperate to achieve hi#h availability usin# the
follo+in#
?roadcast messa#es such as Zheartbeats[
/eer0to0peer I/ soc"ets
2. Cou can confi#ure broadcast communication to use either
I/ unicast
A dedicated I/ multicast address !224.J.J.J throu#h
23K.255.255.255$ and port
3. If heartbeats are not received from a cluster member, the server is
mar"ed as Zfailed[ and its services are not used.
1>0.Cow the Weblo/ic "erver detect a server Gailure?
4. >ebHo#ic clusters detect the failure of a server instance in the
follo+in# +ays
3hrou#h the use of I/ soc"ets
3hrou#h the 'racle >ebHo#ic <erver heartbeat
5. If a server in the cluster unexpectedly closes its soc"et, it is mar"ed as
Zfailed[ and its services are not used.
6. <erver instances use multicast to broadcast heartbeats every 1J
seconds to the other server instances in the cluster.
If three heartbeats are missed from a peer server, the
server is mar"ed as Zfailed[ and its services are not used.
1>3.!xplain about %neJtoJ)an+ Co**unications in W#"?
2. 'racle >ebHo#ic <erver uses one0to0many communication for
.luster+ide *9DI updates
.luster Zheartbeats[
3. ?ecause all one0to0many communications occur over I/ multicast,
+hen you desi#n a cluster, consider the follo+in# factors
If your cluster spans multiple subnets, your net+or"
must be confi#ured to reliably transmit messa#es.
A fire+all can brea" I/ multicast transmissions.
3he multicast address should not be shared +ith other
applications.
5ulticast storms may occur.
1>7.!xplain about (eerJtoJ(eer Co**unications in W#"?
'racle >ebHo#ic <erver uses peer0to0peer communications for
4. Accessin# the nonclustered ob(ects that reside on a remote server
instance in the cluster
5. 1eplicatin# 233/ session states and stateful session -*? states
bet+een a primary and a secondary server
6. Accessin# the clustered ob(ects that reside on a remote server
instance !typically, in a multitiercluster architecture$
1>9.!xplain about )ultitier Co**unications in W#"?
&. 5ultitier clusters re)uire more I/ soc"ets than a combined0tier cluster
'ne soc"et for replicatin# session states
'ne soc"et for each 'racle >ebHo#ic <erver in the -*? cluster,
for accessin# remote ob(ects
2. As an example, usin# a three0node cluster, the +orst0case scenario
+ould be five open soc"ets per server
'ne primary and secondary replicated session
-ach server simultaneously invo"es a remote -*? method on
each node in the cluster.
1>;.Cow *an+ cluster Confi/uration %ptions are available in W#"?
3here are multiple +ays to create and confi#ure an 'racle >ebHo#ic <erver cluster
3. Administration .onsole
4. .onfi#uration >iFard
5. >ebHo#ic <criptin# 3ool !>H<3$
6. 4sin# the .luster 5?ean
1><.!xplain about IwoJ(hase ,eplo+*ent?
&. Applications are deployed usin# t+o0phase deployment !3/D$.
N. Applications are copied to the cluster and activated in t+o phases
/hase 1 Application components and modules are distributed
to the server.
/hase 2 3he application is deployed if phase 1 is successful
and client access is permitted.
K. 3his ensures that an application is available and active on each node
before clients can access it.
1>>.Cow will +ou ,eplo+ Applications to a Cluster?
1J. All nodes must be runnin# before an application is deployed to
a cluster.
11. If phase 2 of the t+o0phase deployment fails, the application is still
deployed to other nodes in thecluster.
12. >ebHo#ic allo+s partial deployment of applications to a partitioned
server.
13. <ession replication for deployed applications may fail if a node is
partitioned at the time of deployment.
Avoid this by usin# the enforce.luster.onstraints ta# +ith
+eblo#ic.Deployer.
'r select the -nable .luster .onstraints chec" box in the
console.
14. Do not chan#e cluster membership +hile deployin# applications to
the cluster.
2@@.!xplain about CII( "ession Gailover?
15. >eb applications use 233/ sessions to trac" information in server
memory for each client.
16. ?y default, +hen a client fails over to another server in the cluster, its
session information is lost.
17.'racle >ebHo#ic <erver supports several Session
!eplication strate#ies to recover sessions from failed servers
In0memory replication
*D?. replication
Bile replication
1N. 1eplication is confi#ured for each >eb application +ithin its
+eblo#ic.xml file.
1K. <imilar options are available for stateful -*? applications.
2@1.!xplain about CII( "ession "tate :eplication in W#"?
1. 'racle >ebHo#ic <erver provides clusterin# support for *</s and servlets by
replicatin# the 233/ session state.
2. 3o benefit from 233/ session state clusterin#, you must ensure that the
session state is persistent, by confi#urin#
In0memory replication
*D?. replication
Bile system replication
3. Cou must also access the cluster via a collection of >eb servers +ith identically
confi#ured proxy plu#0ins or load0balancin# hard+are.
4. <ession persistence is confi#ured usin# the \session0descriptorM element in the
+eblo#ic.xml deploymentdescriptor file.
-ach persistence method has its o+n set of confi#urable parameters.
2@2.!xplain about :eplication ?roups in W#"?
1. A replication #roup is a lo#ical #roupin# of related servers in a cluster.
2. >H< enables you to determine +here to put bac"up ob(ects usin# replication #roups.
3. >H< attempts to
<end bac"up ob(ects to a preferred secondary replication #roup, if it is
confi#ured
<end bac"up ob(ects to a different machine
Avoid sendin# bac"up ob(ects to servers in the same replication #roup
2@0.What is the user of :eplication ?roups in W#"?
1. 1eplication #roups
1epresent a subset of servers +ithin a cluster
2elp to determine the placement of secondary sessions !avoid replicatin#
+ithin the same room, forexample$
Are not explicitly defined in the console0li"e machines and clusters
2. >H< attempts to
<end secondary sessions to servers that are assi#ned to
the preferred secondary replication group of the primary server
Avoid sendin# secondary sessions to servers that are assi#ned to the
same replication #roup as the primary server
2@3.!xplain about InJ)e*or+ :eplication in W#"?
1. -ach userAs session al+ays exists on t+o servers
/rimary
<econdary
2. -very update to the primary session is automatically replicated on the secondary
server, either
<ynchronously !default$
Asynchronously !batch$
3. >H< can replicate
2ttp<ession ob(ects
<tateful session -*?s
4. <ession ob(ects exist on only t+o servers.
5. <econdary
3he server is determined by the replication #roup and machine definition.
3he ob(ect is created immediately after the primary ob(ect is created.
6. /rimary failure ma"es the bac"up ob(ect the primary ob(ect.
2@7.What are all the :eDuire*ents for InJ)e*or+ :eplication in W#"?
1. <ubse)uent re)uests from the same client must have access to the same primary
ob(ect.
2. 3o use in0memory replication for the 233/ session state, clients must access
the cluster usin# either
1. 3he load0balancin# hard+are !>H< a+are$
2. A collection of >eb servers, or a sin#le >eb server, +ith >ebHo#ic proxy plu#0
ins !confi#ured identically$
3. 'racle >ebHo#ic <erver confi#ured +ith 233/.luster<ervlet
2@9.Cow will +ou Confi/urin/ InJ)e*or+ :eplication in W#"?
1. .onfi#ure the proxy server !if applicable$.
2. 'ptionally define replication #roups and7or machines.
3. <pecify the persistence type in the +eblo#ic.xml deployment descriptor: the options include
1. replicated
2. replicatedXifXclustered
3. async0replication0across0cluster
2@;.!xplain about 6,-C :eplication in W#"?
233/ sessions are persisted to a database usin# a common *D?. data source.
3he re)uired data definition lan#ua#e !DDH$ file is available in the
documentation.
"ll members of the cluster have access to any clientAs session for failover
purposes !no primary orsecondary$.
All server instances have access to all sessions.
<ubse)uent re)uests from the same client can be handled by any server.
Oreat failover capability
<i#nificant performance reduction
.han#in# session ob(ects causes !slo+$ database synchroniFation.
2@0.What is the user of :eplication ?roups in W#"?
1eplication #roups
1epresent a subset of servers +ithin a cluster
2elp to determine the placement of secondary sessions !avoid
replicatin# +ithin the same room, for example$
Are not explicitly defined in the console0li"e machines and
clusters
>H< attempts to
<end secondary sessions to servers that are assi#ned to
the preferred secondary replication group of the primary server
Avoid sendin# secondary sessions to servers that are assi#ned
to the same replication #roup as the primary server
2@3.!xplain about InJ)e*or+ :eplication in W#"?
-ach userAs session al+ays exists on t+o servers
/rimary
<econdary
-very update to the primary session is automatically replicated on the
secondary server, either
<ynchronously !default$
Asynchronously !batch$
>H< can replicate
2ttp<ession ob(ects
<tateful session -*?s
<ession ob(ects exist on only t+o servers.
<econdary
3he server is determined by the replication #roup and
machine definition.
3he ob(ect is created immediately after the primary ob(ect is
created.
/rimary failure ma"es the bac"up ob(ect the primary ob(ect.
2@7.What are all the :eDuire*ents for InJ)e*or+ :eplication in W#"?
<ubse)uent re)uests from the same client must have access to the
same primary ob(ect.
3o use in0memory replication for the 233/ session state, clients must
access the cluster usin# either
3he load0balancin# hard+are !>H< a+are$
A collection of >eb servers, or a sin#le >eb server, +ith
>ebHo#ic proxy plu#0ins !confi#ured identically$
'racle >ebHo#ic <erver confi#ured +ith 233/.luster<ervlet
2@9.Cow will +ou Confi/urin/ InJ)e*or+ :eplication in W#"?
.onfi#ure the proxy server !if applicable$.
'ptionally define replication #roups and7or machines.
<pecify the persistence type in the +eblo#ic.xml deployment descriptor:
the options include
replicated
replicatedXifXclustered
async0replication0across0cluster
2@;.!xplain about 6,-C :eplication in W#"?
233/ sessions are persisted to a database usin# a common *D?. data
source.
3he re)uired data definition lan#ua#e !DDH$ file is available in the
documentation.
"ll members of the cluster have access to any clientAs session for
failover purposes !no primary orsecondary$.
All server instances have access to all sessions.
<ubse)uent re)uests from the same client can be handled by any
server.
Oreat failover capability
<i#nificant performance reduction
.han#in# session ob(ects causes !slo+$ database synchroniFation.
2@<.Cow will +ou Confi/urin/ 6,-C :eplication in W#"?
.reate the re)uired table in the database.
.reate a *D?. data source that has read7+rite privile#es for your database.
.onfi#ure *D?. session persistence in the +eblo#ic.xml deployment descriptor.
-x
\session0descriptorM
\persistent0store0typeMjdc\7persistent0store0typeM
\persistent0store0poolM5yData<ource\7persistent0store0poolM
\7session0descriptorM
2@>.6,-C (ersistent Iable Confi/uration
A database table named >HX<-1LH-3X<-<<I'9< must exist +ith read7+rite access

21@.!xplain about Gile :eplication?
Bile replication is similar to *D?. replication, but it persists sessions to a hi#hly
available file system.
<ession state may also be stored in a file.
Bor file0based persistence
Cou must create the directory in +hich to store the file
3he file must have the appropriate access privile#es
211.Cow will +ou Confi/urin/ Gile :eplication in W#"?
.reate a folder shared by all servers on the cluster on a hi#hly available file system.
Assi#n read7+rite privile#es to the folder.
.onfi#ure file session persistence in the +eblo#ic.xml deployment descriptor.
-x
\session0descriptorM
\persistent0store0typeMfile\7persistent0store0typeM
\persistent0store0dirM1mnt1&ls/share\7persistent0store0dirM
\7session0descriptorM
212.!xplain about CrossJCluster :eplication in W#"?
>ebHo#ic provides the ability to replicate 233/ sessions across t+o clusters in separate domains
o 3his is most applicable to clusters that are distributed #eo#raphically.
o .onfi#ure a #lobal proxy to direct clients bac" to the same cluster !Zcluster affinity[$.
o .onfi#ure a specific net+or" channel for cross0cluster communication.
210.When canXt I use Web#o/ic "toreJandJGorward?
Cou canAt use the >ebHo#ic <tore0and0Bor+ard service in the follo+in# situations
1eceivin# from a remote destinationcuse a messa#e driven -*? or implement a client
consumer directly.
<endin# messa#es to a local destinationcsend directly to the local destination.
Bor+ardin# messa#es to prior releases of >ebHo#ic <erver. <ee E. >hat is a messa#in#
brid#eG.
Interoperatin# +ith third0party *5< products !for example, 5E<eries$. <ee E. >hat is a
messa#in# brid#eG.
>hen usin# temporary destinations +ith the *5<1eply3o field to return a response to a
re)uest.
-nvironment +ith lo+ tolerance for messa#e latency. <AB increases latency and may lo+er
throu#hput.
213..!xplain about !*bedded #,A( "erver?
o In >H<, users, #roups, and authoriFation information is stored in an embedded HDA/
server.
o <everal properties can be set to mana#e the HDA/ server, includin#
.redentials
?ac"up settin#s
.ache settin#s
1eplication settin#s
217.Cow will +ou create a ,eplo+*ent (lan?
o 3ools for creatin# a deployment plan
+eblo#ic./lanOenerator
Administration .onsole
o Ooals for creatin# a deployment plan
3o expose the external resource re)uirements of the application as variables in
the deployment plan
3o expose additional confi#urable properties, such as tunin# parameters as
variables in the deployment plan
>H< includes tools to accelerate deployment plan creation.
3he Administration .onsole
Oenerates a s"eleton plan.xml if a plan folder is detected +ith a ne+ly
deployed application
4pdates plan.xml +hen you use the console to modify the deployment
descriptor settin#s
3he +eblo#ic./lanOenerator *ava class can also #enerate a s"eleton plan.xml for an existin#
application.
219..!xplain the relationship between Iransaction and :esource )ana/ers?
o A transaction mana#er coordinates multiple resource mana#ers.
o 3he 2/. protocol is used to coordinate the transaction.
o 3he ^A protocol implements 2/..
21;..What is a topic subscription?
A topic subscription can be thou#ht of as an internal )ueue of messa#es +aitin# to be delivered to a
particular subscriber. 3his internal )ueue accumulates copies of each messa#e published to the topic
after the subscription +as created. .onversely, it does not accumulate messa#es that +ere sent
before the subscription +as created. <ubscriptions are not sharable, only one subscriber may
subscribe to a particular subscription at a time.
21<.!xplain about Irust and Identit+ in ""#?
o <<H and "eystore are confi#ured independently.
o Bor the purpose of bac"+ard compatibility, this release of 'racle >ebHo#ic <erver
supports private "eys and a trusted >ebHo#ic Ieystore provider.
o Identity
/rivate "ey and di#ital certificate !can no+ be loo"ed up directly from the
"eystore, not necessarily as a stand0alone file outside the "eystore$
o 3rust
.ertificates of trusted .ertificate authorities
21K..2o+ +ill you access <<H enabled applicationsG
o >H< uses <<H to secure 233/ and t3 communication.
o 3o use <<H, clients access >H< via the https or t3s protocols.
https77localhost&JJ27order<toc"
t3s77localhost&JJ27use.redit.ard
java server faces
Q1. What is 6"G?
*<B stands for *ava <erver Baces. *<B has set of pre0assembled 4ser Interface !4I$. ?y this it
means complex components are pre0coded and can be used +ith ease. It is event0driven
pro#rammin# model. ?y that it means that *<B has all necessary code for event handlin# and
component or#aniFation. Application pro#rammers can concentrate on application lo#ic rather
sendin# effort on these issues. It has component model that enables third0party components
to be added li"e A*A^.
Q2. What is reDuired for 6"G to /et started?
Bollo+in# thin#s re)uired for *<B
, *DI !*ava <- Development Iit$
, *<B 1.2
, Application <erver !3omcat or any standard application server$
, Inte#rated Development -nvironment !ID-$ -x. 9etbeans 5.5, -clipse 3.2.x, etc.
'nce *DI and Application <erver is do+nloaded and confi#ured, one can copy the *<B (ar files
to *<B pro(ect and could (ust start codin#. 0$
If ID- is used, it +ill ma"e thin#s very smooth and +ill save your time.
Q0. What is 6"G architecture?
*<B +as developed usin# 5L. !a.".a 5odel Lie+ .ontroller$ desi#n pattern so that
applications can be scaled better +ith #reater maintainability. It is driven by *ava
.ommunity /rocess !*./$ and has become a standard. 3he advanta#e of *<B is that itfghs
both a *ava >eb user fgZ interface and a frame+or" that fits +ell +ith the 5L.. It provides
clean separation bet+een presentation and behavior. 4I !a.".a 4ser Interface$ can be created
by pa#e author usin# reusable 4I components and business lo#ic part can be implemented
usin# mana#ed beans.
Q3. Cow 6"G different fro* conventional 6"( B "ervlet )odel?
*<B much more plumbin# that *</ developers have to implement by hand, such as pa#e navi#ation
and validation. 'ne can thin" of *</ and servlets as the fgoeassembly lan#ua#efgG under the hood
Q7. Cow the co*ponents of 6"G are rendered? An !xa*ple
In an application add the *<B libraries. Burther in the .(sp pa#e one has to add the ta# library li"e
\Ya ta#lib uriT=http77(ava.sun.com7(sf7core= prefixT=f=YM
\Ya ta#lib uriT=http77(ava.sun.com7(sf7html= prefixT=h=YM
'r one can try ^5H style as +ell
\Gxml versionT=1.J=GM
\(sproot versionT=2.J= xmlns(spT=http77(ava.sun.com7*</7/a#e=
xmlnsfT=http77(ava.sun.com7(sf7core=
xmlnshT=http77(ava.sun.com7(sf7html=M
'nce this is done, one can access the *<B components usin# the prefix attached. If +or"in# +ith an
ID- !a.".a Inte#rated Development -nvironment$ one can easily add *<B but +hen +or"in# +ithout
them one also has to update7ma"e the faces0confi#.xml and have to populate the file +ith classes i.e.
5ana#ed ?eans bet+een
\faces0confi#M \7faces0confi#M ta#s
Q9. Cow to declare the 'avi/ation :ules for 6"G?
9avi#ation rules tells *<B implementation +hich pa#e to send bac" to the bro+ser after a form has
been submitted. Bor ex. for alo#in pa#e, after the lo#in #ets successful, it should #o to 5ain pa#e, else
to return on the same lo#in pa#e, for that +e have to code as
\navi#ation0ruleM
\from0vie+0idM7lo#in.(sp\7from0vie+0idM
\navi#ation0caseM
\from0outcomeMlo#in\7from0outcomeM
\to0vie+0idM7main.(sp\to0vie+0idM
\7navi#ation0caseM
\navi#ation0caseM
\from0outcomeMfail\7from0outcomeM
\to0vie+0idM7lo#in.(sp\to0vie+0idM
\7navi#ation0caseM
\7navi#ation0ruleM
from0outcome to be match +ith action attribute of the command button of the lo#in.(sp as
\hcommandbutton valueT=Ho#in= actionT=lo#in=7M
<econdly, it should also match +ith the navi#ation rule in face0confi#.xml as
\mana#ed0beanM
\mana#ed0bean0nameMuser\7mana#ed0bean0nameM
\mana#ed0bean0classMcore.(sf.Ho#in?ean\7mana#ed0bean0classM
\mana#ed0bean0scopeMsession\7mana#ed0bean0scopeM
\7mana#ed0beanM
In the 4I component, to be declared 7 used as
\hinput3ext valueT=d6user.name;=7M
value attribute refers to name property of the user bean.
Q;. Cow do I confi/ure the confi/uration file?
3he confi#uration file used is our old +eb.xml, if +e use some ID- it +ill be pretty simple to #enerate
but the contents +ill be somethin# li"e belo+
\Gxml versionTQ)uote:1.JQ)uote: encodin#TQ)uote:43B0NQ)uote:GM
\+eb0app versionTQ)uote:2.4Q)uote: xmlnsTQ)uote:http77(ava.sun.com7xml7ns7(2eeQ)uote:
xmlnsxsiTQ)uote:http77+++.+3.or#72JJ17^5H<chema0instanceQ)uote:
xsischemaHocationTQ)uote:http77(ava.sun.com7xml7ns7(2ee http77(ava.sun.\context0paramM
\param0nameMcom.sun.faces.verify'b(ects\7param0nameM
\param0valueMfalse\7param0valueM
\7context0paramM
\context0paramM
\param0nameMcom.sun.faces.validate^ml\7param0nameM
\param0valueMtrue\7param0valueM
\7context0paramM
\context0paramM
\param0nameM(avax.faces.<3A3-X<ALI9OX5-32'D\7param0nameM
\param0valueMclient\7param0valueM
\7context0paramM
\servletM
\servlet0nameMBaces <ervlet\7servlet0nameM
\servlet0classM(avax.faces.+ebapp.Baces<ervlet\7servlet0classM
\load0on0startupM1\7load0on0startupM
\7servletM
\servlet0mappin#M
\servlet0nameMBaces <ervlet\7servlet0nameM
\url0patternM7faces78\7url0patternM
\7servlet0mappin#M
\session0confi#M
\session0timeoutM
3J
\7session0timeoutM
\7session0confi#M
\+elcome0file0listM
\+elcome0fileM
index.(sp
\7+elcome0fileM
\7+elcome0file0listM
\7+eb0appM
3he uni)ue thin# about this file is Gservlet mappin#G. *<B pa#es are processed by a servlet "no+n to
be part of *<B implementation code. In the example above, it has extension of .faces. It +ould be
+ron# to point your bro+ser tohttp77localhostNJNJ75y*<B7lo#in.(sp, but it has to be
http77localhostNJNJ75y*<B7lo#in.faces. If you +ant that your pa#es to be
+ith .(sf, it can be done +ith small modification 0$,
\servlet0mappin#M
\servlet0nameMBaces <ervlet\7servlet0nameM
\url0patternM8.(sf\7url0patternM
\servlet0mappin#M
Q<. What is 6"G fra*ework?
*<B frame+or" can be explained +ith the follo+in# dia#ram
As can be seen in Bi#ure 1, *<B interacts +ith .lient Devices +hich ties to#ether +ith
presentation, navi#ation and event handlin# and business lo#ic of +eb tier model. 2ence *<B is limited
to presentation lo#ic 7 tier. Bor Database tier i.e. Database and >eb services one has to rely on other
services.
of the hi#h0level *<B frame+or".
Q>. Cow does 6"G depict the )8C 1a.k.a )odel 8iew Controller2 *odel?
3he data that is manipulated in form or the other is done by model. 3he data presented to
user in one form or the other is done by vie+. *<B is connects the vie+ and the model. Lie+
can be depicted as sho+n by
\hinput3ext valueT=d6user.name;=7M
*<B acts as controller by +ay of action processin# done by the user or tri##erin# of an
event. Bor ex.
\hcommandbutton valueT=Ho#in= actionT=lo#in=7M
, this button event +ill tri##ered by the user on ?utton press, +hich +ill invo"e the lo#in ?ean
as stated in the faces0confi#.xml file. 2ence, it could be summariFed as belo+ 4ser ?utton
.lic" 0M form submission to server 0M invocation of ?ean class 0M result thro+n by ?ean class
cau#ht be navi#ation rule 0M navi#ation rule based on action directs to specific pa#e.
Q1@. What does it *ean b+ renderin/ of pa/e in 6"G?
-very *<B pa#e as described has various components made +ith the help of *<B library. *<B
may contain hform, hinput3ext, hcommand?utton, etc. -ach of these are rendered
!translated$ to 235H output. 3his process is called encodin#. 3he encodin# procedure also
assi#ns each component +ith a uni)ue ID assi#ned by frame+or". 3he ID #enerated is
random.
Q11. What is 6ava"erver Gaces?
*ava<erver Baces !*<B$ is a user interface !4I$ frame+or" for *ava +eb applications. It is
desi#ned to si#nificantly ease the burden of +ritin# and maintainin# applications that run on a
*ava application server and render their 4Is bac" to a tar#et client. *<B provides ease0ofuse in
the follo+in# +ays
, 5a"es it easy to construct a 4I from a set of reusable 4I components
, <implifies mi#ration of application data to and from the 4I
, 2elps mana#e 4I state across server re)uests
, /rovides a simple model for +irin# client0#enerated events to server0side application code
, Allo+s custom 4I components to be easily built and re0used
5ost importantly, *<B establishes standards +hich are desi#ned to be levera#ed by tools to
provide a developer experience +hich is accessible to a +ide variety of developer types,
ran#in# from corporate developers to systems pro#rammers. A =corporate developer= is
characteriFed as an individual +ho is proficient in +ritin# procedural code and business lo#ic,
but is not necessarily s"illed in ob(ect0oriented pro#rammin#. A =systems pro#rammer=
understands ob(ect0oriented fundamentals, includin# abstraction and desi#nin# for re0use. A
corporate developer typically relies on tools for development, +hile a system pro#rammer may
define his or her tool as a text editor for +ritin# code. 3herefore, *<B is desi#ned to be tooled,
but also exposes the frame+or" and pro#rammin# model as A/Is so that it can be used
outside of tools, as is sometimes re)uired by systems pro#rammers.
Q12. Cow to pass a para*eter to the 6"G application usin/ the &:# strin/?
if you have the follo+in# 41H http77yourXserver7yourXapp7product.(sfGidT&&&, you access
the passin# parameter id +ith the follo+in# lines of (ava code
Baces.ontext fc T Baces.ontext.#et.urrentInstance!$:
<trin# id T !<trin#$ fc.#et-xternal.ontext!$.#et1e)uest/arameter5ap!$.#et!=id=$:
Brom the pa#e, you can access the same parameter usin# the predefined variable +ith name
param. Bor example,
\houtput3ext valueT=d6paramR%id%S;= 7M
'ote Cou have to call the (sf pa#e directly and usin# the servlet mappin#.
Q10. Cow to add context path to &:# for output#ink?
.urrent *<B implementation does not add the context path for outputHin" if the defined path
starts +ith %7%. 3o correct this problem use
d6faces.ontext.external.ontext.re)uest.ontext/ath; prefix at the be#innin# of the
outputHin" value attribute.
Bor example
\houtputHin" valueT=d6faces.ontext.external.ontext.re)uest.ontext/ath;7my/a#e.faces=M
Q13 Cow to /et current pa/e &:# fro* backin/ bean?
Cou can #et a reference to the 233/ re)uest ob(ect via Baces.ontext li"e this
Baces.ontext fc T Baces.ontext.#et.urrentInstance!$:
2ttp<ervlet1e)uest re)uest T !2ttp<ervlet1e)uest$ fc.#et-xternal.ontext!$.#et1e)uest!$:
and then use the normal re)uest methods to obtain path information. Alternatively,
context.#etLie+1oot!$.#etLie+Id!$:
+ill return you the name of the current *</ !*<B vie+ IDs are basically (ust *</ path
names$.
Q17. Cow to access web.x*l init para*eters fro* java code?
Cou can #et it usin# external.ontext #etInit/arameter method. Bor example, if you have
\context0paramM
\param0nameMconnection<trin#\7param0nameM
\param0valueM(dbcoraclethinscott7ti#eracartman1521'KJ1D?\7param0valueM
\7context0paramM
Cou can access this connection strin# +ith
Baces.ontext fc T Baces.ontext.#et.urrentInstance!$:
<trin# connection T fc.#et-xternal.ontext!$.#etInit/arameter!=connection<trin#=$:
Q19. Cow to access web.x*l init para*eters fro* jsp pa/e?
Cou can #et it usin# init/aram pre0defined *<B -H valiable.
Bor example, if you have
\context0paramM
\param0nameMproductId\7param0nameM
\param0valueM2JJ4E4\7param0valueM
\7context0paramM
Cou can access this parameter +ith d6init/aramR%productId%S; . Bor example
/roduct Id \houtput3ext valueT=d6init/aramR%productId%S;=7M
Q1;. Cow to ter*inate the session?
In order to terminate the session you can use session invalidate method.
3his is an example ho+ to terminate the session from the action method of a bac"in# bean
public <trin# lo#out!$ 6
Baces.ontext fc T Baces.ontext.#et.urrentInstance!$:
2ttp<ession session T !2ttp<ession$ fc.#et-xternal.ontext!$.#et<ession!false$:
session.invalidate!$:
return =lo#inXpa#e=:
;
3he follo+in# code snippet allo+s to terminate the session from the (sp pa#e
\Y session.invalidate!$: YM \credirect urlT=lo#in/a#e.(sf= 7M
Q1<. Cow to i*ple*ent L(lease$ Wait...L pa/e?
3he client0side solution mi#ht be very simple. Cou can +rap the (sp pa#e !or part of it you
+ant to hide$ into the DIL, then you can add one more DIL that appears +hen user clic"s the
submit button. 3his DIL can contain the animated #if you spea" about or any other content.
<cenario +hen user clic"s the button, the *ava<cript function is called. 3his function hides the
pa#e and sho+s the =>ait= DIL. Cou can customiFe the loo"0n0fill +ith .<< if you li"e.
3his is a +or"in# example
\Ya ta#lib uriT=http77(ava.sun.com7(sf7html= prefixT=h= YM
\Ya ta#lib uriT=http77(ava.sun.com7(sf7core= prefixT=f= YM
\fload?undle basenameT=demo.bundle.5essa#es= varT=5essa#e=7M
\htmlM
\headM
\titleMInput 9ame /a#e\7titleM
\scriptM
function #o+ait!$ 6
document.#et-lement?yId!=main=$.style.visibilityT=hidden=:
document.#et-lement?yId!=+ait=$.style.visibilityT=visible=:
;
\7scriptM
\7headM
\body b#colorT=+hite=M
\fvie+M
\div idT=main=M
\h1M\houtput3ext valueT=d65essa#e.inputnameXheader;=7M\7h1M
\hmessa#es styleT=color red=7M
\hform idT=helloBorm=M
\houtput3ext valueT=d65essa#e.prompt;=7M
\hinput3ext idT=user9ame= valueT=d6Oet9ame?ean.user9ame;= re)uiredT=true=M
\fvalidateHen#th minimumT=2= maximumT=2J=7M
\7hinput3extM
\hcommand?utton onclic"T=#o+ait!$= idT=submit= actionT=d6Oet9ame?ean.action;=
\7hformM
\7divM
\div idT=+ait= styleT=visibilityhidden: position absolute: top J: left J=M
\table +idthT=1JJY= hei#ht T=3JJpx=M
\trM
\td ali#nT=center= vali#nT=middle=M
\h2M/lease, +ait...\7h2M
\7tdM
\7trM
\7tableM
\7divM
\7fvie+M
\7bodyM
\7htmlM
If you +ant to have an animated #if of the =>ait= /a#e, the #if should be reloaded after the
form is (ust submitted. <o, assi#n the id for your ima#e and then add reload code that +ill be
called after some short delay. Bor the example above, it mi#ht be
\scriptM
function #o+ait!$ 6
document.#et-lement?yId!=main=$.style.visibilityT=hidden=:
document.#et-lement?yId!=+ait=$.style.visibilityT=visible=:
+indo+.set3imeout!%sho+/ro#ress!$%, 5JJ$:
;
function sho+/ro#ress!$6
var +# T document.#et-lement?yId!=+ait#if=$:
+#.srcT+#.src:
;
\7scriptM
....
....
....
\im# idT=+ait#if= srcT=animated.#if=M
Q1>. Cow to reload the pa/e after 8alueChan/e#istener is invoked?
At the end of the Lalue.han#eHistener, call
Baces.ontext.#et.urrentInstance!$.render1esponse!$
Q2@. Cow to download (,G file with 6"G?
3his is an code example ho+ it can be done +ith action listener of the bac"in# bean.
Add the follo+in# method to the bac"in# bean
public void vie+/df!Action-vent event$ 6
<trin# filename T =filename.pdf=:
77 use your o+n method that reads file to the byte array
byteRS pdf T #et3he.ontent'f3heBile!filename$:
Baces.ontext faces T Baces.ontext.#et.urrentInstance!$:
2ttp<ervlet1esponse response T !2ttp<ervlet1esponse$
faces.#et-xternal.ontext!$.response.set.ontent3ype!=application7pdf=$:
response.set.ontentHen#th!pdf.len#th$:
response.set2eader! =.ontent0disposition=, =inline: filenameTi==@file9ame@=i==$:
try 6
<ervlet'utput<tream out:
out T response.#et'utput<tream!$:
out.+rite!pdf$:
; catch !I'-xception e$ 6
e.print<tac"3race!$:
;
faces.response.omplete!$:
;
3his is a (sp file snippet
\hcommand?utton immediateT=true= actionHistenerT=d6bac"in#?ean.vie+/df;=
valueT=1ead
Q21. Cow to show Confir*ation ,ialo/ when user Click the Co**and #ink?
hco**and#ink assi/n the onclick attribute for internal use. "o$ +ou cannot use it to
write +our own code. Ihis proble* will fixed in the 6"G 1.2. Gor the current 6"G
version +ou can use on*ousedown event that occurs before onclick.
Sscript lan/ua/eKLjavascriptLH
function Confir*,elete1link2 N var delete K confir*1E,o +ou want to ,elete?E2R if
1delete KK
true2 N link.onclick12R O O SBscriptH . . . . Shco**and#ink actionKLdeleteL
on*ousedownKLreturn Confir*,elete1this2RLH ShoutputIext valueKLdelete itLBH
SBhco**and#inkH
Q22. What is the different between /et:eDuest(ara*eter)ap12 and
/et:eDuest(ara*eter8alues)ap12
/et:eDuest(ara*eter8alues)ap12 si*ilar to /et:eDuest(ara*eter)ap12$ but
contains *ultiple values for for the para*eters with the sa*e na*e. It is i*portant
if +ou one of the co*ponents such as Shselect)an+H.
Q20. Is it possible to have *ore than one Gaces Confi/uration file?
Yes. You can define the list of the confi/uration files in the web.x*l.
Ihis is an exa*ple
ScontextJpara*H
Spara*Jna*eHjavax.faces.C%'GI?TGI#!"SBpara*Jna*eH
Spara*JvalueHBW!-JI'GBfacesJconfi/Jnavi/ation.x*l$BW!-JI'GBfacesJ
beans.x*lSBpara*JSBcontextJpara*H
'ote ,o not re/ister BW!-JI'GBfacesJconfi/.x*l file in the web.x*l . %therwise$
the 6"G i*ple*entation will process it twice.
Ci there$ I /uess the 'ote colu*n should have been *eant or intended for
Lfacesconfi/.x*lL file as thats the default confi/uration file for 6"G 1which is si*ilar
to strutsconfi/.x*l for "trutsUU2. facesJcontext.x*l file sounds like the user defined
confi/ file si*ilar to the afore*entioned two x*l files.
Q23. Cow to *ask actual &:# to the 6"G pa/e?
YouEll need to i*ple*ent +our own version of javax.faces.8iewCandler which does
what +ou need. Ihen$ +ou re/ister +our own view handler in facesJconfi/.x*l.
CereEs a si*ple abstract 8iewCandler +ou can extend and then i*ple*ent the 0
abstract *ethods for. Ihe abstract *ethods +ou override here are where +ouEll do
+our conversions toBfro* &:I to ph+sical paths on the file s+ste*. Ihis infor*ation
is just passed ri/ht alon/ to the default 8iewCandler for 6"G to deal with in the usual
wa+. Gor exa*ple$ +ou could override these *ethods to add and re*ove the file
extension of an inco*in/ view id 1like in +our exa*ple2$ for extensionJless view
&:Is.
i*port java.io.I%!xceptionR
i*port java.util.#ocaleR
i*port javax.faces.Gaces!xceptionR
i*port javax.faces.application.8iewCandlerR
i*port javax.faces.co*ponent.&I8iew:ootR
i*port javax.faces.context.GacesContextR
i*port or/.apache.co**ons.lo//in/.#o/R
i*port or/.apache.co**ons.lo//in/.#o/Gactor+R
BVV
V A facade view handler which *aps &:Is into actual ph+sical views that the
V underl+in/ i*ple*entation can deal with re/ularl+.
V Iherefore$ all internal references to view ids$ for exa*ple in facesJconfi/$
V will use the path to the ph+sical files. !ver+thin/ publici=ed$ however$ will
V see a LconvertedL B facade url.
VB
public abstract class "i*pleConverter8iewCandler extends 8iewCandler N
private static final #o/ #%? K
#o/Gactor+./et#o/1"i*pleConverter8iewCandler.class2R
private final 8iewCandler baseR
public "i*pleConverter8iewCandler18iewCandler base2 N
this.base K baseR
O
BVV
V ,istin/uishes a &:I fro* a ph+sical file view.
V Iests if a view id is in the expected for*at JJ the for*at correspondin/
V to the ph+sical file views$ as opposed to the &:Is.
V Ihis test is necessar+ because 6"G takes the view I, fro* the
V facesJconfi/ navi/ation$ and calls render8iew12 on it$ etc.
VB
public abstract boolean is8iewGor*at1GacesContext context$ "trin/ viewId2R
BVV
V Convert a private file path 1view id2 into a public &:I.
VB
public abstract "trin/ convert8iewIo&:I1GacesContext context$ "trin/ viewId2R
BVV
V Convert a public &:I into a private file path 1view id2
V note uri alwa+s starts with LBLR
VB
public abstract "trin/ convert&:IIo8iew1GacesContext context$ "trin/ uri2R
public "trin/ /etAction&:#1GacesContext context$ "trin/ viewId2 N
BB '%I! this is used for G%:) actions.
"trin/ new8iewId K convert8iewIo&:I1context$ viewId2R
#%?.debu/1L/et8iewId(ath L 4 viewId 4 LJHL 4 new8iewId2R
return base./etAction&:#1context$ new8iewId2R
O
private "trin/ doConvert&:IIo8iew1GacesContext context$ "trin/ reDuest&:I2 N
if 1is8iewGor*at1context$ reDuest&:I22 N
return reDuest&:IR
O else N
return convert&:IIo8iew1context$ reDuest&:I2R
O
O
public void render8iew1GacesContext context$ &I8iew:oot viewIo:ender2
throws I%!xception$ Gaces!xception N
if 1null KK context ZZ null KK viewIo:ender2
throw new 'ull(ointer!xception1Lnull context or viewL2R
"trin/ reDuest&:I K viewIo:ender./et8iewId12R
"trin/ new8iewId K doConvert&:IIo8iew1context$ reDuest&:I2R
#%?.debu/1Lrender8iew L 4 reDuest&:I 4 LJHL 4 new8iewId2R
viewIo:ender.set8iewId1new8iewId2R
base.render8iew1context$ viewIo:ender2R
O
public &I8iew:oot restore8iew1GacesContext context$ "trin/ viewId2 N
"trin/ new8iewId K doConvert&:IIo8iew1context$ viewId2R
#%?.debu/1Lrestore8iew L 4 viewId 4 LJHL 4 new8iewId2R
return base.restore8iew1context$ new8iewId2R
O
public #ocale calculate#ocale1GacesContext ar/@2 N
return base.calculate#ocale1ar/@2R
O
public "trin/ calculate:enderFitId1GacesContext ar/@2 N
return base.calculate:enderFitId1ar/@2R
O
public &I8iew:oot create8iew1GacesContext ar/@$ "trin/ ar/12 N
return base.create8iew1ar/@$ ar/12R
O
public "trin/ /et:esource&:#1GacesContext ar/@$ "trin/ ar/12 N
return base./et:esource&:#1ar/@$ ar/12R
O
public void write"tate1GacesContext ar/@2 throws I%!xception N
base.write"tate1ar/@2R
O
O
Q27. Cow to print out ht*l *arkup with houtputIext?
3he houtput3ext has attribute escape that allo+s to escape the html mar"up. ?y default, it
e)uals to =true=. It means all the special symbols +ill be replaced +ith %Q% codes. If you set it
to =false=, the text +ill be printed out +ithout ecsapin#.
Bor example, \houtput3ext valueT=\bM3his is a text\7bM=7M
+ill be printed out li"e
\bM3his is a text\7bM
In case of \houtput3ext escapeT=false= valueT=\bM3his is a text\7bM=7M
you +ill #et
Ihis is a text
Q29. hinput"ecret field beco*es e*pt+ when pa/e is reloaded. Cow to fix this?
<et redisplayTtrue, it is false by default.
)ervlets
10 7s it the ?servlets? directory or the ?servlet? directory?
Bor *ava >eb <erver
on the file system, it%s =servlets=
ci*ava>eb<erver1.1iservletsiDate<ervlet.class
in a 41H path, it%s =servlet=
http77+++.stin"y.com7servlet7Date<ervlet
20 How do 7 su""ort both @A< and =B)< "rotocol ,rom the same )ervlet?
3he easy +ay is, (ust support /'<3, then have your doOet method call your do/ost method
public void doOet!2ttp<ervlet1e)uest re), 2ttp<ervlet1esponse res$
thro+s <ervlet-xception, I'-xception
6
do/ost!re), res$:
;
30 How do 7 ensure that my servlet is thread6sa,e?
3his is actually a very complex issue. A fe+ #uidelines
1. 3he init!$ method is #uaranteed to be called once per servlet instance, +hen the servlet is
loaded. Cou don%t have to +orry about thread safety inside this method, since it is only called
by a sin#le thread, and the +eb server +ill +ait until that thread exits before sendin# any
more threads into your service!$ method.
2. -very ne+ client re)uest #enerates !or allocates$ a ne+ thread: that thread calls the service!$
method of your servlet !+hich may in turn call do/ost!$, doOet!$ and so forth$.
3. 4nder most circumstances, there is only one instance of your servlet, no matter ho+ many
client re)uests are in process. 3hat means that at any #iven moment, there may be many
threads runnin# inside the service!$ method of your solo instance, all sharin# the same
instance data and potentially steppin# on each other%s toes. 3his means that you should be
careful to s+nchroni=e access to shared data !instance variables$ usin# the synchroniFed
"ey+ord.
!9ote that the server +ill also allocate a ne+ instance if you re#ister the servlet +ith a ne+
name and, e.#., ne+ init parameters.$
4. 9ote that you need not !and should not$ synchroniFe on local data or parameters. And
especially you shouldn%t synchroniFe the service!$ method] !'r do/ost!$, doOet!$ et al.$
5. A simple solution to synchroniFin# is to al+ays synchroniFe on the servlet instance itself usin#
Q)uot:synchroniFed !this$ 6 ... ;Q)uot:. 2o+ever, this can lead to performance bottlenec"s:
you%re usually better off synchroniFin# on the data ob(ects themselves.
6. If you absolutely can%t deal +ith synchroniFin#, you can declare that your servlet
Q)uot:implements <in#le3hread5odelQ)uot:. 3his empty interface tells the +eb server to only
send one client re)uest at a time into your servlet. Brom the *avaDoc 20uot3If the target
servlet is flagged &ith this interface4 the servletprogrammer is guaranteed that no t&o threads
&ill e5ecute concurrently the service method of that servlet6 ,his guarantee is ensured y
maintaining a pool of servlet instances for each such servlet4 and dispatching each service
call to a free servlet6 In essence4 if the servlet implements this interface4 the servlet &ill e
thread safe620uot3 9ote that this is not an ideal solution, since performance may suffer
!dependin# on the siFe of the instance pool$, plus it%s more difficult to share data across
instances than +ithin a sin#le instance.
<ee also >hat%s a better approach for enablin# thread0safe servlets and *</sG
<in#le3hread5odel Interface or <ynchroniFationG
7. 3o share data across successive or concurrent re)uests, you can use either instance variables
or class0static variables, or use <ession 3rac"in#.
8. 3he destroy!$ method is not necessarily as clean as the init!$ method. 3he server calls
destroy either after all service calls have been completed, or after a certain number of
seconds have passed, +hichever comes first. 3his means that other threads mi#ht be runnin#
service re)uests at the same time as your destroy!$ method is called] <o be sure to
synchroniFe, and7or +ait for the other re)uests to )uit. <un%s <ervlet 3utorial has an example
of ho+ to do this +ith reference countin#.
K. destroy!$ can not thro+ an exception, so if somethin# bad happens, call lo#!$ +ith a helpful
messa#e !li"e the exception$. <ee the Q)uot:closin# a *D?. connectionQ)uot: example in
<un%s 3utorial.
#0 What is the di,,erence between 24+ encodin81 24+ rewritin81 H<;+ esca"in81 and entity
encodin8?
&:# !ncodin/ is a process of transformin# user input to a .OI form so it is fit for travel across the
net+or" 00 basically, strippin# spaces and punctuation and replacin# +ith escape characters. 41H
Decodin# is the reverse process. 3o perform these operations, call (ava.net.41H-ncoder.encode!$ and
(ava.net.41HDecoder.decode!$ !the latter +as !finally]$ added to *DI 1.2, a"a *ava 2$.
!xa*ple chan#in# =>e%re d1]= into =>eY2&re@Y231Y21=
&:# :ewritin/ is a techni)ue for savin# state information on the user%s bro+ser bet+een pa#e hits.
It%s sort of li"e coo"ies, only the information #ets stored inside the 41H, as an additional parameter.
3he 2ttp<ession A/I, +hich is part of the <ervlet A/I, sometimes uses 41H 1e+ritin# +hen coo"ies are
unavailable.
!xa*ple chan#in# \A 21-BT=nextpa#e.html=M into
\A 21-BT=nextpa#e.html:WsessionidWTD<*B<DIB<HDB--I'-=M !or +hatever the actual syntax is: I
for#et offhand$ !4nfortunately, the method in the <ervlet A/I for doin# 41H re+ritin# for session
mana#ement is called encode41H!$. <i#h...$
3here%s also a feature of the Apache +eb server called 41H 1e+ritin#: it is enabled by the modXre+rite
module. It re+rites 41Hs on their +ay in to the server, allo+in# you to do thin#s li"e automatically
add a trailin# slash to a directory name, or to map old file names to ne+ file names. 3his has nothin#
to do +ith servlets. Bor more information, see the Apache BAE
!http77+++.apache.or#7docs7misc7BAE.htmldre+rite0more0confi#$ .
$0 How do 7 u"load a ,ile to my servlet or J)=?
'n the client side, the client%s bro+ser must support form0based upload. 5ost modern bro+sers do,
but there%s no #uarantee. Bor example,
\B'15 -9.3C/-T%multipart7form0data% methodT%/'<3% actionT%7myservlet%M
\I9/43 3C/-T%file% 9A5-T%mptest%M
\I9/43 3C/-T%submit% LAH4-T%upload%M
\7B'15M
3he input type Q)uot:fileQ)uot: brin#s up a button for a file select box on the bro+ser to#ether +ith a
text field that ta"es the file name once selected. 3he servlet can use the O-3 method parameters to
decide +hat to do +ith the upload +hile the /'<3 body of the re)uest contains the file data to parse.
>hen the user clic"s the =4pload= button, the client bro+ser locates the local file and sends it usin#
233/ /'<3, encoded usin# the 5I5-0type multipart7form0data. >hen it reaches your servlet, your
servlet must process the /'<3 data in order to extract the encoded file. Cou can learn all about this
format in 1B. 1N6&.
4nfortunately, there is no method in the <ervlet A/I to do this. Bortunately, there are a number of
libraries available that do. <ome of these assume that you +ill be +ritin# the file to dis": others return
the data as an Input<tream.
*ason 2unter%s 5ultipart1e)uest !available from http77+++.servlets.com7$
Apache *a"arta .ommons 4pload !pac"a#e or#.apache.commons.upload$ =ma"es it easy to
add robust, hi#h0performance, file upload capability to your servlets and +eb applications=
./arse1B.1N6& !available from http77+++.servletcentral.com7$.
2ttp5ulti/art/arser by Anil 2emra(ani, at the isavvix .ode -xchan#e
3here is a multipart7form parser availailable from Anders Iristensen !http77+++0
u".hpl.hp.com7people7a"7(ava7,a"ahplb.hpl.hp.com$ at http77+++0
u".hpl.hp.com7people7a"7(ava7dutils.
*ava5ail also has 5I5-0parsin# routines !see the /urple <ervlet 1eferences$.
*un Inamori has +ritten a class called or#.apache.tomcat.re)uest./arse5ime +hich is available
in the 3omcat.L< tree.
*</<mart has a free set of *</ for doin# file upload and do+nload.
4pload?ean by *avaUoom claims to handle most of the hassle of uploadin# for you, includin#
+ritin# to dis" or memory.
3here%s an 4pload 3a# in dot*
'nce you process the form0data stream into the uploaded file, you can then either +rite it to dis",
+rite it to a database, or process it as an Input<tream, dependin# on your needs. <ee 2o+ can I
access or create a file or folder in the current directory from inside a servletG and other )uestions in
the <ervletsBiles 3opic for information on +ritin# files from a <ervlet.
(lease note that you can%t access a file on the client system directly from a servlet: that +ould be a
hu#e security hole. Cou have to as" the user for permission, and currently form0based upload is the
only +ay to do that.
%0 How does a servlet communicate with a J)= "a8e?
3he follo+in# code snippet sho+s ho+ a servlet instantiates a bean and initialiFes it +ith B'15 data
posted by a bro+ser. 3he bean is then placed into the re)uest, and the call is then for+arded to the
*</ pa#e, ?ean1.(sp, by means of a re)uest dispatcher for do+nstream processin#.
public void do/ost !2ttp<ervlet1e)uest re)uest,
2ttp<ervlet1esponse response$ 6

try 6
#ovi.Borm?ean f T ne+ #ovi.Borm?ean!$:
<trin# id T re)uest.#et/arameter!=id=$:
f.set9ame!re)uest.#et/arameter!=name=$$:
f.setAddr!re)uest.#et/arameter!=addr=$$:
f.setA#e!re)uest.#et/arameter!=a#e=$$:
77use the id to compute
77additional bean properties li"e info
77maybe perform a db )uery, etc.
77 . . .
f.set/ersonaliFationInfo!info$:
re)uest.setAttribute!=f?ean=,f$:
#et<ervlet.onfi#!$.#et<ervlet.ontext!$.#et1e)uestDispatcher
!=7(sp7?ean1.(sp=$.for+ard!re)uest, response$:
; catch !-xception ex$ 6
. . .
;
;
3he *</ pa#e ?ean1.(sp can then process f?ean, after first extractin# it from the default re)uest scope
via the use?ean action.
\(spuse?ean idT=f?ean= classT=#ovi.Borm?ean= scopeT=re)uest=7M
\(sp#et/roperty nameT=f?ean= propertyT=name= 7M
\(sp#et/roperty nameT=f?ean= propertyT=addr= 7M
\(sp#et/roperty nameT=f?ean= propertyT=a#e= 7M
\(sp#et/roperty nameT=f?ean= propertyT=personaliFationInfo= 7M
'0 WhatCs a better a""roach ,or enablin8 thread6sa,e servlets and J)=s? )in8le<hread;odel
7nter,ace or )ynchroniDation?
Althou#h the <in#le3hread5odel techni)ue is easy to use, and +or"s +ell for lo+ volume sites, it does
not scale +ell. If you anticipate your users to increase in the future, you may be better off
implementin# explicit synchroniFation for your shared data. 3he "ey ho+ever, is to effectively
minimiFe the amount of code that is synchronFied so that you ta"e maximum advanta#e of
multithreadin#.
Also, note that <in#le3hread5odel is pretty resource intensive from the server%s perspective. 3he most
serious issue ho+ever is +hen the number of concurrent re)uests exhaust the servlet instance pool. In
that case, all the unserviced re)uests are )ueued until somethin# becomes free 0 +hich results in poor
performance. <ince the usa#e is non0deterministic, it may not help much even if you did add more
memory and increased the siFe of the instance pool.
(0 !an a servlet maintain a J<A 2ser<ransaction ob&ect across multi"le servlet invocations?
9o. A *3A transaction must start and finish +ithin a sin#le invocation !of the service!$ method$. 9ote
that this )uestion does not address servlets that maintain and manipulate *D?. connections, includin#
a connection%s transaction handlin#.
90 How does the "er,ormance o, J)= "a8es com"are with that o, servlets? How does it
com"are with =erl scri"ts?
3he performance of *</ pa#es is very close to that of servlets. 2o+ever, users may experience a
perceptible delay +hen a *</ pa#e is accessed for the very first time. 3his is because the *</ pa#e
under#oes a =translation phase= +herein it is converted into a servlet by the *</ en#ine. 'nce this
servlet is dynamically compiled and loaded into memory, it follo+s the servlet life cycle for re)uest
processin#. 2ere, the (spInit!$ method is automatically invo"ed by the *</ en#ine upon loadin# the
servlet, follo+ed by the X(sp<ervice!$ method, +hich is responsible for re)uest processin# and
replyin# to the client. Do note that the lifetime of this servlet is non0deterministic 0 it may be removed
from memory at any time by the *</ en#ine for resource0related reasons. >hen this happens, the *</
en#ine automatically invo"es the (spDestroy!$ method allo+in# the servlet to free any previously
allocated resources.
<ubse)uent client re)uests to the *</ pa#e do not result in a repeat of the translation phase as lon#
as the servlet is cached in memory, and are directly handled by the servlet%s service!$ method in a
concurrent fashion !i.e. the service!$ method handles each client re)uest +ithin a seperate thread
concurrently.$
3here have been some recent studies contrastin# the performance of servlets +ith /erl scripts runnin#
in a =real0life= environment. 3he results are favorable to servlets, especially +hen they are runnin# in
a clustered environment.
1-0 How do 7 call one servlet ,rom another servlet?
R <hort ans+er there are several +ays to do this, includin#
use a 1e)uestDispatcher
use a 41H.onnection or 233/.lient
send a redirect
call #et<ervlet.ontext!$.#et<ervlet!name$ !deprecated, doesn%t +or" in 2.1@$
0 Alex S
It depends on +hat you mean by =call= and +hat it is you see" to do and +hy you see" to do it.
If the end result needed is to invo"e the methods then the simplest mechanism +ould be to treat the
servlet li"e any (ava ob(ect , create an instance and call the mehods.
If the idea is to call the service method from the service method of another servlet, AIA for+ardin#
the re)uest, you could use the 1e)uestDispatcher ob(ect.
If, ho+ever, you +ant to #ain access to the instance of the servlet that has been loaded into memory
by the servlet en#ine, you have to "no+ the alias of the servlet. !2o+ it is defined depends on the
en#ine.$ Bor example, to invo"e a servlet in *<DI a servlet can be named by the property
myname.codeTcom.sameer.servlets.5y<ervlet
3he code belo+ sho+s ho+ this named servlet can be accessed in the service method of another
servlet
public void service !2ttp<ervlet1e)uest re)uest, 2ttp<ervlet1esponse response$
thro+s <ervlet-xception, I'-xception 6
...
5y<ervlet msT!5y<ervlet$ #et<ervlet.onfi#!$.#et<ervlet.ontext!$.#et<ervlet!=myname=$:
...
;
3hat said, 3his +hole apporach of accessin# servlets in another servlets has been deprecated in the
2.1 version of the servlet A/I due to the security issues. 3he cleaner and better apporach is to (ust
avoid accessin# other servlets directly and use the 1e)uestDispatcher instead.
110 What are all the di,,erent :inds o, servers? .)uch as Web )ervers1 A""lication )ervers1
etc0
3he servers involved in handlin# and processin# a user%s re)uest brea" do+n into a fe+ basic types,
each of +hich may have one or more tas"s it solves. 3his flexibility #ives developers a #reat deal of
po+er over ho+ applications +ill be created and deployed, but also leads to confusion over +hat
server is able to, or should, perform a specific tas".
<tartin# at the basic level, a user is typically submittin# a re)uest to a system throu#h a +eb bro+ser.
!>e are conveniently i#norin# all other types of clients !15I, .'1?A, .'57D.'5, .ustom, etc..$ for
the time bein# for purposes of clarity.$ 3he +eb re)uest must be received by a Web
"erver !other+ise "no+n as an CII( "erver$ of some sort. 3his +eb server must handle standard
233/ re)uests and responses, typically returnin# 235H to the callin# user. .ode that executes +ithin
the server environment may be .OI driven, <ervlets, A</, or some other server0side pro#rammin#
lan#ua#e, but the end result is that the +eb server +ill pass bac" 235H to the user.
3he +eb server may need to execute an application in response to the users re)uest. It may be
#eneratin# a list of ne+s items, or handlin# a form submission to a #uest boo". If the server
application is +ritten as a *ava <ervlet, it +ill need a place to execute, and this place is typically called
a "ervlet !n/ine. Dependin# on the +eb server, this en#ine may be internal, external, or a
completely different product. 3his en#ine is continually runnin#, unli"e a traditional .OI environment
+here a .OI script is started upon each re)uest to the server. 3his persistance #ives a servlet
connection and thread poolin#, as +ell as an easy +ay to maintain state bet+een each 233/ re)uest.
*</ pa#es are usually tied in +ith the servlet en#ine, and +ould execute +ithin the same
space7application as the servlets.
3here are many products that handle the +eb servin# and the servlet en#ine in different manners.
9etscape7i/lanet -nterprise <erver builds the servlet en#ine directly into the +eb server and runs
+ithin the same process space. Apache re)uires that a servlet en#ine run in an external process, and
+ill communicate to the en#ine via 3./7I/ soc"ets. 'ther servers, such as 5< II< don%t officially
support servlets, and re)uire add0on products to add that capability.
>hen you move on to -nterprise *ava?eans !and other *2-- components li"e *5< and .'1?A$ you
move into the application server space. An Application "erver is any server that supplies additional
functionality related to enterprise computin# 00 for instance, load balancin#, database access classes,
transaction processin#, messa#in#, and so on.
!6- Application "ervers provide an -*? container, +hich is the environment that beans +ill execute
in, and this container +ill mana#e transactions, thread pools, and other issues as necessary. 3hese
application servers are usually stand0alone products, and developers +ould tie their servlets7*</
pa#es to the -*? components via remote ob(ect access A/Is. Dependin# on the application server,
pro#rammers may use .'1?A or 15I to tal" to their beans, but the baseline standard is to use *9DI
to locate and create -*? references as necessary.
9o+, one thin# that confuses the issue is that many application server providers include some or all of
these components in their product. If you loo" at >ebHo#ic !http77+++.beasys.com7$ you +ill find
that >ebHo#ic contains a +eb server, servlet en#ine, *</ processor, *5< facility, as +ell as an -*?
container. 3heoretically a product li"e this could be used to handle all aspects of site development. In
practice, you +ould most li"ely use this type of product to mana#e7serve -*? instances, +hile
dedicated +eb servers handle the specific 233/ re)uests.
120 )hould 7 override the service.0 method?
9o. It provides a fair bit of house"eepin# that you%d (ust have to do yourself. If you need to do
somethin# re#ardless of +hether the re)uest is e.#., a /'<3 or a O-3, create a helper method and call
that at the be#innin# of e.#., do/ost!$ and doOet!$.
130 How can my a""lication 8et to :now when a Htt")ession is removed .when it time6
outs0?
Define a class, say <ession3imeout9otifier, that implements
(avax.servlet.http.2ttp<ession?indin#Histener. .reate a <ession3imeout9otifier ob(ect and add it to
the user session. >hen the session is removed, <ession3imeout9otifier.value4nbound!$ +ill be called
by the servlet en#ine. Cou can implement value4nbound!$ to do +hatever you +ant.
1#0 Why use J)= when we can do the same thin8 with servlets?
R'ri#inal )uestion >hy should I use *</ +hen there is already servlet technolo#y available for servin#
dynamic contentGS
>hile *</ may be #reat for servin# up dynamic >eb content and separatin# content from
presentation, some may still +onder +hy servlets should be cast aside for *</. 3he utility of servlets is
not in )uestion. 3hey are excellent for server0side processin#, and, +ith their si#nificant installed
base, are here to stay. In fact, architecturally spea"in#, you can vie+ *</ as a hi#h0level abstraction
of servlets that is implemented as an extension of the <ervlet 2.1 A/I. <till, you shouldn%t use servlets
indiscriminately: they may not be appropriate for everyone. Bor instance, +hile pa#e desi#ners can
easily +rite a *</ pa#e usin# conventional 235H or ^5H tools, servlets are more suited for bac"0end
developers because they are often +ritten usin# an ID- 00 a process that #enerally re)uires a hi#her
level of pro#rammin# expertise.
>hen deployin# servlets, even developers have to be careful and ensure that there is no ti#ht couplin#
bet+een presentation and content. Cou can usually do this by addin# a third0party 235H +rapper
pac"a#e li"e htmlIona to the mix. ?ut even this approach, thou#h providin# some flexibility +ith
simple screen chan#es, still does not shield you from a chan#e in the presentation format itself. Bor
example, if your presentation chan#ed from 235H to D235H, you +ould still need to ensure that
+rapper pac"a#es +ere compliant +ith the ne+ format. In a +orst0case scenario, if a +rapper
pac"a#e is not available, you may end up hardcodin# the presentation +ithin the dynamic content. <o,
+hat is the solutionG 'ne approach +ould be to use both *</ and servlet technolo#ies for buildin#
application systems.
1$0 How do 7 send in,ormation and data bac: and ,orth between a""let and servlet usin8
the H<<= "rotocol?
4se the standard (ava.net.41H class, or =roll your o+n= usin# (ava.net.<oc"et. <ee the 233/ spec at
>3. for more detail.
9ote 3he servlet cannot initiate this connection] If the servlet needs to asynchronously send a
messa#e to the applet, then you must open up a persistent soc"et usin# (ava.net.<oc"et !on the
applet side$, and (ava.net.<erver<oc"et and 3hreads !on the server side$.
1%0 !an 7 8et the "ath o, the current servlet where it lives on the ,ile system .not its 24+0?
3ry usin#
re)uest.#et1eal/ath!re)uest.#et<ervlet/ath!$$
An example may be
out.println!re)uest.#et1eal/ath!re)uest.#et<ervlet/ath!$$$:
1'0 How can 7 daisy chain servlets to8ether such that the out"ut o, one servlet serves as
the in"ut to the next?
3here are t+o common methods for chainin# the output of one servlet to another servlet
i. the first method is the aliasin# +hich describes a series of servlets to be executed
ii. the second one is to define a ne+ 5I5-03ype and associate a servlet as handlers As I don%t
really use the second one, I%ll focus on the aliasin#.
3o chain servlets to#ether, you have to specify a se)uential list of servlets and associate it to an alias.
>hen a re)uest is made to this alias, the first servlet in the list is invo"ed, processed its tas" and sent
the ouptut to the next servlet in the list as the re)uest ob(ect. 3he output can be sent a#ain to
another servlets.
3o accomplish this method, you need to confi#ure your servlet en#ine !*1un, *ava>eb server,
*<erv ...$.
Bor example to confi#ure *1un for servlet chainin#, you select the *<- service !*1un servlet en#ine$ to
access to the *<- <ervice .onfi# panel. Cou have (ust to define a ne+ mappin# rule +here you define
your chainin# servlet.
Het say 7servlets7chain<ervlet for the virtual path and a comma separated list of servlets as srvA,srv?.
<o +hen you invo"e a re)uest li"e http77localhost7servlets7chain<ervlet, internally the servlet srvA
+ill be invo"ed first and its results +ill be piped into the servlet srv?.
3he srvA servlet code should loo" li"e
public class srvA extends 2ttp<ervlet 6
...
public void doOet !...$ 6
/rint>riter out Tres.#et>riter!$:
rest.set.ontent3ype!=text7html=$:
...
out.println!=2ello .hainin# servlet=$:
;
;
All the servlet srv? has to do is to open an input stream to the re)uest ob(ect and read the data into a
?uffered1eader ob(ect as for example
?uffered1eader b T ne+ ?uffered1eader! ne+
Input<tream1eader!re).#etInput<tream!$ $ $:
<trin# data T b.readHine!$:
b.close!$:
After that you can format your output +ith the data.
It should +or" strai#thfor+ard +ith *ava >eb <erver or *serv too. *ust loo" at in their documentation
to define an alias name. 2ope that it%ll help.
1(0 Why there are no constructors in servlets?
A servlet is (ust li"e an applet in the respect that it has an init!$ method that acts as a constrcutor.
<ince the servlet environment ta"es care of instantiatin# the servlet, an explicit constructor is not
needed. Any initialiFation code you need to run should be placed in the init!$ method since it #ets
called +hen the servlet is first loaded by the servlet container.
190 How to handle multi"le concurrent database requestsEu"dates when usin8 JD! with
servlets?
All the dbms provide the facility of loc"s +henever the data is bein# modified. 3here can be t+o
scenarios
1. 5ultiple database updates on different ro+s, if you are usin# servlets the servlets +ill open
multiple connections for different users. In this case there is no need to do additional
pro#rammin#.
2. If database updates are on the same ro+ then the ro+s are loc"ed automatically by the dbms,
hence +e have to send re)uests to the dbms repeatatively until the loc" is released by dbms.
3his issue is dealt +ith in the *D?. documentation: loo" up =3ransactions= and =auto0commit=. It can
#et pretty confusin#.
2-0 What is the di,,erence between @eneric)ervlet and Htt")ervlet?
Oeneric<ervlet is for servlets that mi#ht not use 233/, li"e for instance B3/ servlets. 'f course, it
turns out that there%s no such thin# as B3/ servlets, but they +ere tryin# to plan for future #ro+th
+hen they desi#ned the spec. 5aybe some day there +ill be another subclass, but for no+, al+ays use
2ttp<ervlet.
210 How do you share session ob&ects between servlets and J)=?
<harin# sessions bet+een a servlet and a *</ pa#e is strai#ht for+ard. *</ ma"es it a little easy by
creatin# a session ob(ect and ma"in# it availabe already. In a servlet you +ould have to do it yourself.
3his is ho+
77create a session if one is not created already no+
2ttp<ession session T re)uest.#et<ession!true$:
77assi#n the session variable to a value.
session.putLalue!=variable=,=value=$:
in the (sp pa#e this is ho+ you #et the session value
\Y
session.#etLalue!=varible=$:
YM
220 What is a servlet?
A servlet is a +ay of extendin# your +eb server +ith a *ava pro#ram to perform tas"s previously dealt
+ith by .OI scripts or proprietary server extension frame+or"s.
230 7s there any method to unload a servlet ,rom Web )erver memory without restartin8
the server?
3here is no standard method7mechanism to unload a servlet from memory. <ome servers, li"e *><,
provide the means to load and unload servlets from their administration module. 'thers, li"e 3omcat,
re)uire you to (ust replace the >A1 file.
2#0 What distin8uishes a Javaean ,rom a )ervlet?
*ava?eans are a set of rules to follo+ to create reusable soft+are components, or beans. 3his contains
properties and events. At the end you have a component +hich could be examined by a pro#ram !li"e
an ID-$ to allo+ the user of your *ava?ean component to confi#ure it and to run in its *ava pro#rams.
<ervlets are *ava classes runnin# in a <ervlet en#ine implementin# a particular interface <ervlet,
forcin# you to implement some methods !service!$$. 3he servlet is an extension of your +eb server
+here this servlet is runnin# on and only lets you "no+ +hen a user re)uests a O-3 or /'<3 calls
from a +eb pa#e to your servlet.
<o, both have nothin# in common except *ava.
2$0 How much data we can store in a session ob&ect?
Any amount of data can be stored there because the session is "ept on the server side.
3he only limitation is sessionId len#th, +hich shouldn%t exceed j4JJJ bytes 0 this limitation is implied
by 233/ header len#th limitation to 4Ib since sessionId may be stored in the coo"ie or encoded in
41H !usin# =&:# rewritin/=$ and the coo"ie specification says the siFe of coo"ie as +ell as 233/
re)uest !e.#. O-3 7document.htmlin$ cannot be lon#er then 4"b.
2%0 What is the di,,erence between the do@et and do=ost methods?
doOet is called in response to an 233/ O-3 re)uest. 3his happens +hen users clic" on a lin", or enter
a 41H into the bro+ser%s address bar. It also happens +ith some 235H B'15s !those +ith
5-32'DT=O-3= specified in the B'15 ta#$.
do/ost is called in response to an 233/ /'<3 re)uest. 3his happens +ith some 235H B'15s !those
+ith 5-32'DT=/'<3= specified in the B'15 ta#$.
?oth methods are called by the default !superclass$ implementation of service in the 2ttp<ervlet base
class. Cou should override one or both to perform your servlet%s actions. Cou probably shouldn%t
override service!$.
2'0 What is the di,,erence between encode4edirect2rl and encode24+?
encode41H and encode1edirect41H are methods of the 2ttp1esponse ob(ect. ?oth re+rite a ra+ 41H
to include session data if necessary. !If coo"ies are on, both are no0ops.$
encode41H is for normal lin"s inside your 235H pa#es.
encode1edirect41H is for a lin" you%re passin# to response.send1edirect!$. It has sli#htly different
syntax re)uirements too #ory to #et into here.
2(0 !an 7 use )ystem3exit.0 in servlets?
Oac"] 9o no no no no...
At best, you%ll #et a security exception. At +orst, you%ll ma"e the servlet en#ine, or maybe the entire
+eb server, )uit. Cou don%t really +ant to do that, huhG 0$
290 7 am o"enin8 a sin8le JD! connection in my init.0 method3 Do 7 need to synchroniDe
on the !onnection or the )tatement ob&ect?
Cou shouldn%t have to. If your *D?. driver supports multiple connections, then the various
create<tatement methods +ill #ive you a thread0safe, reentrant, independent <tatement that should
+or" 'I, even if other re)uests7threads are also accessin# other <tatements on the same .onnection.
'f course, crossin# your fin#ers never hurts... 5any early *D?. drivers +ere not re0entrant. 3he
modern versions of *D?. drivers should +or" 'I, but there are never any #uarantees.
4sin# connection poolin# +ill avoid the +hole issue, plus +ill lead to improved performance. <ee this
BAE for more information.
3-0 How can 7 determine the name and version number o, the servlet or J)= en8ine that 7
am usin8?
Brom +ithin a servlet, you can invo"e the <ervlet.ontext.#et<erverInfo!$ method as follo+s
<trin# this<erverT #et<ervlet.onfi#!$.#et<ervlet.ontext!$.#et<erverInfo!$:
If you are usin# *</, you can use this expression
\YT application.#et<erverInfo!$ YM
310 How can 7 8et the absolute 24+ o, a servletEJ)= "a8e at runtime?
Cou can #et all the necessary information to determine the 41H from the re)uest ob(ect. 3o
reconstruct the absolute 41H from the scheme, server name, port, 41I and )uery strin# you can use
the 41H class from (ava.net. 3he follo+in# code fra#ment +ill determine your pa#e%s absolute 41H
<trin# file T re)uest.#et1e)uest41I!$:
if !re)uest.#etEuery<trin#!$ ]T null$ 6
file @T %G% @ re)uest.#etEuery<trin#!$:
;
41H reconstructed41H T ne+ 41H!re)uest.#et<cheme!$,
re)uest.#et<erver9ame!$,
re)uest.#et<erver/ort!$,
file$:
out.println!41H.to<trin#!$$:
320 Why do @eneric)ervlet and Htt")ervlet im"lement the )erialiDable inter,ace?
Oeneric<ervlet and 2ttp<ervlet implement the <erialiFable interface so that servlet en#ines can
=hybernate= the servlet state +hen the servlet is not in use and reinstance it +hen needed or
to duplicate servlet instances for better load balancin#. I don%t "no+ if or ho+ current servlet en#ines
do this, and it could have serious implications, li"e brea"in# references to ob(ects #otten in the init!$
method +ithout the pro#rammer "no+in# it. /ro#rammers should be a+are of this pitfall and
implement servlets +hich are stateless as possible, dele#atin# data store to <ession ob(ects or to the
<ervlet.ontext. In #eneral stateless servlets are better because they scale much better and are
cleaner code.
330 How does one choose between overridin8 the do@et.01 do=ost.01 and service.0
methods?
3he differences bet+een the doOet!$ and do/ost!$ methods are that they are called in the 2ttp<ervlet
that your servlet extends by its service!$ method +hen it recieves a O-3 or a /'<3 re)uest from a
233/ protocol re)uest.
A O-3 re)uest is a re)uest to #et a resource from the server. 3his is the case of a bro+ser re)uestin#
a +eb pa#e. It is also possible to specify parameters in the re)uest, but the len#th of the parameters
on the +hole is limited. 3his is the case of a form in a +eb pa#e declared this +ay in html \form
methodT=O-3=M or \formM.
A /'<3 re)uest is a re)uest to post !to send$ form data to a resource on the server. 3his is the case
of of a form in a +eb pa#e declared this +ay in html \form methodT=/'<3=M. In this case the siFe of
the parameters can be much #reater.
3he Oeneric<ervlet has a service!$ method that #ets called +hen a client re)uest is made. 3his means
that it #ets called by both incomin# re)uests and the 233/ re)uests are #iven to the servlet as they
are !you must do the parsin# yourself$.
3he 2ttp<ervlet instead has doOet!$ and do/ost!$ methods that #et called +hen a client re)uest is
O-3 or /'<3. 3his means that the parsin# of the re)uest is done by the servlet you have the
appropriate method called and have convenience methods to read the re)uest parameters.
N#,7: the doOet!$ and do/ost!$ methods !as +ell as other 2ttp<ervlet methods$ are called by the
service!$ method.
.oncludin#, if you must respond to O-3 or /'<3 re)uests made by a 233/ protocol client !usually a
bro+ser$ don%t hesitate to extend 2ttp<ervlet and use its convenience methods.
If you must respond to re)uests made by a client that is not usin# the 233/ protocol, you must use
service!$.
3#0 How do servlets di,,er ,rom 4;7? What are the advanta8es and disadvanta8es o, each
technolo8y?
<ervlets extend the server0side functionality of a +ebsite. <ervlets communicate +ith other
application!s$ on that server !or any other server$ and perform tas"s above and beyond the =normal=
static 235H document. A servlet can receive a re)uest to #et some information throu#h -*? from one
or more databases, then convert this data into a static 235H7>5H pa#e for the client to see, for
example. -ven if the servlet tal"s to many other applications all over the +orld to #et this information,
it still loo"s li"e it happened at that +ebsite.
15I !1emote 5ethod Invocation$ is (ust that 0 a +ay to invo"e methods on remote machines. It is
+ay for an application to tal" to another remote machine and execute different methods, all the +hile
appearin# as if the action +as bein# performed on the local machine.
<ervlets !or *</$ are mainly used for any +eb0related activity such as online ban"in#, online
#rocery stores, stoc"tradin#, etc. >ith servlets, you need only to "no+ the +eb address and the pa#es
displayed to you ta"e care of callin# the different servlets !or actions +ithin a servlet$ for you. 4sin#
15I, you must bind the 15I server to an I/ and port, and the client +ho +ishes to tal" to the remote
server must "no+ this I/ and port, unless of course you used some "ind of in0bet+een loo"up utility,
+hich you could do +ith !of all thin#s$ servlets.
3$0 How can we use a servlet as a "roxy ,or communications between two a""lets?
'ne +ay to accomplish this is to have the applets communicate via 3./7I/ soc"ets to the servlet. 3he
servlet +ould then use a custom protocol to receive and push information bet+een applets. 2o+ever,
this solution does have fire+all problems if the system is to be used over and Internet verses an
Intranet.
3%0 How can 7 desi8n my servletEJ)= so that query results 8et dis"layed on several "a8es1
li:e the results o, a search en8ine? Aach "a8e should dis"lay1 say1 1- records each
and when the next lin: is clic:ed1 7 should see the nextE"revious 1- records and so
on3
4se a *ava ?ean to store the entire result of the search that you have found. 3he servlet +ill then set
a pointer to the first line to be displayed in the pa#e and the number of lines to display, and force a
display of the pa#e. 3he Action in the form +ould point bac" to the servlet in the *</ pa#e +hich
+ould determine +hether a next or previous button has been pressed and reset the pointer to
previous pointer @ number of lines and redisplay the pa#e. 3he *</ pa#e +ould have a scriplet to
display data from the *ava ?ean from the start pointer set to the maximum number of lines +ith
buttons to allo+ previous or next pa#es to be selected. 3hese buttons +ould be displayed based on
the pa#e number !i.e. if first then don%t display previous button$.
3'0 How do 7 deal with multi6valued "arameters in a servlet?
Instead of usin# #et/arameter!$ +ith the <ervlet1e)uest, as you +ould +ith sin#le0valued parameters,
use the #et/arameterLalues!$ method. 3his returns a <trin# array !or null$ containin# all the values of
the parameter re)uested.
3(0 How can 7 "ass data retrieved ,rom a database by a servlet to a J)= "a8e?
'ne of the better approaches for passin# data retrieved from a servlet to a *</ is to use the 5odel 2
architecture as sho+n belo+
?asically, you need to first desi#n a bean +hich can act as a +rapper for storin# the resultset returned
by the database )uery +ithin the servlet. 'nce the bean has been instantiated and initialiFed by
invo"in# its setter methods by the servlet, it can be placed +ithin the re)uest ob(ect and for+arded to
a display *</ pa#e as follo+s
com.foo.db?ean bean T ne+ com.foo.db?ean!$:
77call setters to initialiFe bean
re).setAttribute!=db?ean=, bean$:
urlT=...=: 77relative url for display (sp pa#e
<ervlet.ontext sc T #et<ervlet.ontext!$:
1e)uestDispatcher rd T sc.#et1e)uestDispatcher!url$:
rd.for+ard!re), res$:
3he bean can then be accessed +ithin the *</ pa#e via the use?ean ta# as
\(spuse?ean idT=db?ean= classT=com.foo.db?ean= scopeT=re)uest=7M
...
\Y
77iterate throu#h the ro+s +ithin db?ean and
77access the values usin# a scriptlet
YM
Also, it is best to desi#n your application such that you avoid placin# beans into the session unless
absolutely necessary. /lacin# lar#e ob(ects +ithin the session imposes a heavy burden on the
performance of the servlet en#ine. 'f course, there may be additional desi#n considerations to ta"e
care of 0 especially if your servlets are runnin# under a clustered or fault0tolerant architecture.
390 How can 7 use a servlet to 8enerate a site usin8 ,rames?
In #eneral, loo" at each frame as a uni)ue document capable of sendin# its o+n re)uests and
receivin# its o+n responses. Cou can create a top servlet !say, Brame<ervlet$ that upon invocation
creates the frame layout you desire and sets the <1. parameters for the frame ta#s to be another
servlet, a static pa#e or any other le#al value for <1..
0000000000000000000000 <A5/H- 0000000000000000000000
public void doOet!2ttp<ervlet1e)uest re)uest,
2ttp<ervlet1esponse response$ thro+s <ervlet-xception, I'-xception 6
response.set.ontent3ype!=text7html=$:
/rint>riter out T ne+ /rint>riter !response.#et>riter!$$:
out.println!==$:
out.println!=Cour 3itle=$:
77 definin#the three ro+s of Brames for the main pa#e
77 top frmX1
77 middle frmX2
77 bottom frmX3
out.println!==$:
out.println!==$:
out.println!==$:
out.println!==$:
out.println!==$:
out.println!==$:
out.println!==$:
out.close!$:
00000000000000000000000000 -9D 000000000000000000000000000000000000000000
>here 5enu<ervlet and Dummy<ervlet provide content and behavior for the frames #enerated by
Brame<ervlet.
#-0 What is H<<= tunnelin81 in the 8eneral sense?
233/ tunnelin# is a #eneral techni)ue +hereby arbitrary data may be sent via an 233/ connection to
and from .OI scripts or *ava <ervlets on a >eb server. 3his is done by serialiFin# the data to be
transmitted into a stream of bytes, and sendin# an 233/ messa#e +ith content type
=application7octet0stream=.
233/ tunnelin# is also referred to as Bire+all tunnelin#.
#10 How do 7 handle 5B4;s with multi"le ,orm elements .e383 radio buttons0 usin8 the
same name?
Bor radio buttons, the 235H spec assumes that a #iven #roup of buttons +ill have the same 9A5- and
different LAH4-s: the bro+ser ma"es sure that only one button per #roup name +ill be selected !at
most$. <o you can (ust call re)uest.#et/arameter!=#roupname=$.
\input typeT=radio= nameT=toppin#= valueT=cheese= chec"edM.heese
\input typeT=radio= nameT=toppin#= valueT=pepperoni=M/epperoni
\input typeT=radio= nameT=toppin#= valueT=anchovies=MAnchovies
If the user selects =/epperoni= then re)uest.#et/arameter!=toppin#=$ +ill return the strin#
=pepperoni=.
Bor lists usin# the \select multipleM B'15 ta#, multiple values can be returned for the same
parameter name. >hen that can happen, use re)uest.#et/arameterLalues!=param=$ +hich returns a
<trin#RS you can iterate throu#h.
It%s bad form !so to spea"$, but you can also duplicate other element types, li"e
9ame 1 \input typeT=text= nameT=name= valueT=Dic"=M
9ame 2 \input typeT=text= nameT=name= valueT=*ane=M
3hese also #et returned in an array by re)uest.#et/arameterLalues!$.
#20 How do 7 se"arate "resentation .H<;+0 ,rom business lo8ic .Java0 when usin8
servlets?
Almost anybody +ho has ever +ritten a servlet can identify +ith this one. >e all "no+ it%s bad for to
embed 235H code in our (ava source: it%s lame to have to recompile and re0deploy every time you
+ant an 235H element to loo" a bit different. ?ut +hat are our choices hereG 3here are t+o basic
options:
1. &se 6"( *ava <erver /a#es allo+s you to embed *ava code or the results of a servlet into your
235H. Cou could, for instance, define a servlet that #ives a stoc" )uote, then use the ta# in a *</
pa#e to embed the output. ?ut then, this brin#s up the same problem: +ithout discipline, your
content7presentation and pro#ram lo#ic are a#ain meshed. I thin" the ideal here is to completely
separate the t+o.
2. &se a te*platin/Bparsin/ s+ste* 2mm...I "no+ you%re about to rant about re0inventin# the
+heel, but it%s not that bad !see belo+$. /lus, it really does pay to ta"e this approach: you can have a
#roup of pro#rammers +or"in# on the *ava code, and a #roup of 235H producers maintainin# the
interface. <o no+ you probably +ant to "no+ ho+ to do it...so read on.
&se ""IU
1emember <<IG It hasn%t #otten much attention in recent years because of embeddable scriptin#
lan#ua#es li"e A</ and *</, but it still remains a viable option. 3o levera#e it in the servlet +orld, I
believe the best +ay is to use an A/I called <<I for *ava from Areane. 3his A/I +ill let you emulate
<<I commands from a templatin# system, and much more. It +ill let you execute any command on
any system, includin# executin# (ava classes] It also comes +ith several utility classes for creatin#
stateful 235H form elements, tables for use +ith iteration, and much more. It%s also open source, so
it%s free and you can t+ea" it to your heart%s content] Cou can read the <<I for *ava documentation for
detailed info, but the follo+in# is an example of its use.
2ere%s the servlet
import (avax.servlet.8:
import (avax.servlet.http.8:
import (ava.io.8:
import (ava.util.8:
import com.areane.+++.ssi.8:
public class <<I3emplatin#<ervlet extends 2ttp<ervlet 6
private <trin# templateBilesDirectory T =diipro(ectsiiidemoiitemplatesii=: 772olds path
to template files

7882andles O-3 re)uests: defers every re)uest to the /'<3 processor87
public void doOet!2ttp<ervlet1e)uest re), 2ttp<ervlet1esponse res$
thro+s <ervlet-xception, I'-xception, Bile9otBound-xception 6do/ost!re), res$:;

7882andles all re)uests. /rocesses the re)uest,
8saves the values, parses the file, then feeds the file to the out stream87
public void do/ost!2ttp<ervlet1e)uest re), 2ttp<ervlet1esponse res$
thro+s <ervlet-xception, I'-xception, Bile9otBound-xception 6
2ttp<ession ses T re).#et<ession!true$:

/roperties context T null:
if!!context T !/roperties$ses.#etLalue!=user.context=$$ TT null$ 6 77if properties doesn%t
already exist, create it.
context T ne+ /roperties!$:
;

77>rite parameters to /roperties ob(ect
-numeration param9ames T re).#et/arameter9ames!$:
<trin# cur9ame, curLal:
+hile!param9ames.has5ore-lements!$$ 6
cur9ame T !<trin#$param9ames.next-lement!$:
curLal T re).#et/arameter!cur9ame$:
context.set/roperty!cur9ame, curLal$:
;

77<ave the values to the session
ses.putLalue!=user.context=, context$:

77/arse the pa#e and stream to the client
<trin# template9ame T re).#et/arameter!=template=$: 77 Oet the file name of the
template to use
res.set.ontent3ype!=text7html=$:
<si/a#e pa#e T <si/arser.parse!this.templateBilesDirectory @ template9ame$: 77/arsin#
occurs here
pa#e.+rite!res.#et>riter!$, context$: 77<tream to the client

pa#e T null: 77clean up
;
;
9o+, (ust create a template file, pass the servlet the template file name, and have at it]
#30 5or an H<;+ 5B4; with multi"le )2;7< buttons1 how can a servlet ond di,,erently ,or
each button?
3he servlet +ill respond differently for each button based on the html that you have placed in the
235H pa#e. Het%s explain.
Bor a submit button the 235H loo"s li"e \input typeTsubmit nameT=Heft= valueT=left=M. A servlet
could extract the value of this submit by usin# the #et/arameter!=Heft=$ from the 2ttp1e)uest ob(ect.
It follo+s then that if you have 235H +ithin a B'15 that appears as
\input typeTsubmit nameT=Direction= valueT=left=M
\input typeTsubmit nameT=Direction= valueT=ri#ht=M
\input typeTsubmit nameT=Direction= valueT=up=M
\input typeTsubmit nameT=Direction= valueT=do+n=M
3hen the /et(ara*eter1L,irectionL2 from the 2ttp1e)uest +ould extract the value pressed by the
user, either =left=, =ri#ht=, =up= or =do+n=. A simple comparision in the servlet +ith the these values
could occur and processin# based on the submit button +ould be performed.
<imiliarly,for submit buttons +ith different names on a pa#e, each of these values could be extracted
usin# the/et(ara*eter12 call and acted on. 2o+ever, in a situation +here there are multiple
buttons, common practice +ould be to use one name and multiple values to identify the button
pressed.
##0 What is meant by the term ?business lo8ic??
=?usiness lo#ic= is (ust a fancy +ay of sayin# =code.= 0$
5ore precisely, in a three0tier architecture, business lo#ic is any code that is not specifically related to
storin# and retrievin# data !that%s =data stora#e code=$, or to formattin# data for display to the user
!that%s =presentation lo#ic=$. It ma"es sense, for many reasons, to store this business lo#ic in separate
ob(ects: the middle tier comprises these ob(ects. 2o+ever, the divisions bet+een the three layers are
often blurry, and business lo#ic is more of an ideal than a reality in most pro#rams. 3he main point of
the term is, you +ant some+here to store the lo#ic and =business rules= !another buFF+ord$ of your
application, +hile "eepin# the division bet+een tiers clear and clean.
#$0 How can 7 ex"licitly unload a servlet or call the destroy method?
In #eneral, you can%t. 3he <ervlet A/I does not specify +hen a servlet is unloaded or ho+ the destroy
method is called. Cour servlet en#ine !ie the implementation of the interfaces in the *<DI$ mi#ht
provide a +ay to do this, probably throu#h its administration interface7tool !li"e >ebshpere or *><$.
5ost servlet en#ines +ill also destroy and reload your servlet if they see that the class file!s$ have
been modified.
#%0 What is a servlet bean?
A servlet bean is a serialiFable servlet that follo+s the *ava?eans component architecture, basically
offerin# #etter7setter methods.
As lon# as you subclass Oeneric<ervlet72ttp<ervlet, you are automatically <erialiFable.
If your +eb server supports them, +hen you install the servlet in the +eb server, you can confi#ure it
throu#h a property sheet0li"e interface.
#'0 Why do we need to call su"er3init.con,i80 in the init method o, a servlet?
*ust do as you%re told and you +on%t #et hurt] 0$
?ecause if you don%t, then the confi# ob(ect +ill #et lost. *ust extend 2ttp<ervlet, use init!$ !no
parameters$ and it%ll all +or" o".
Brom the *avadoc init!$ 0 A convenience method +hich can be overridden so that there%s no need to
call super.init!confi#$.
#(0 What is a servlet en8ine?
A =servlet en#ine= is a pro#ram that plu#s in to a +eb server and runs servlets. 3he term is obsolete:
the preferred term no+ is =servlet container= since that applies both to plu#0in en#ines and to stand0
alone +eb servers that support the <ervlet A/I.
#90 Which is the most e,,icient .i3e3 "rocessin8 s"eed0 way to create a server a""lication
that accesses a database: A )ervlet usin8 JD!F a J)= "a8e usin8 a Javaean to carry
out the db accessF or J)= combined with a )ervlet? Are these my only choices?
Cour )uestion really should be bro"en in t+o.
10>hat is the most efficient +ay of servin# pa#es from a *ava ob(ectG. 3here you have a clear +inner
in the <ervlet. Althou#ht if you are #oin# to chan#e the static content of the pa#e often is #oin# to be
a pain because you%ll have to chan#e *ava code. 3he second place in speed is for *</ pa#es. ?ut,
dependin# on your application, the difference in speed bet+een *</ pa#es and ra+ servlets can be so
small that is not +orth the extra +or" of servlet pro#rammin#.
20>hat is the most efficient +ay of accessin# a database from *avaG. If *D?. is the +ay you +ant to
#o the I%d su##est to pic" as many drivers as you can !II,III,IL or +athever$ and benchmar" them.
3ype I uses a *D?.7'D?. brid#e and usually has lousy performance. A#ain, #o for the simplest
!usually type IL driver$ solution if that meets you performance needs.
Bor database applications, the performance bottlenec" is usually the database, not the +eb
server7en#ine. In this case, the use of a pac"a#e that access *D?. +ith connection poolin# at the
application level used from *</ pa#es !+ith or +ithouth beans as middle+are$ is the usual choice. 'f
course, your applications re)uirements may vary.
$-0 How can 7 chan8e the "ort o, my Java Web )erver ,rom (-(- to somethin8 else?
It is very simple. *ALA >-? <-1L-1 comes +ith remote >eb administration tool. Cou can access this
+ith a +eb bro+ser.
Administration tool is located on port KJKJ on your +eb server. 3o chan#e port address for +eb
server
1. Access tool !http77hostnameKJKJ$
2. -nter 4ser Id7/ass+ord !by default it is admin7admin$
3. <elect service !>eb service$
4. .lic" on =mana#e= button. Cou +ill #et a popup screen +ith all settin#s.
5. .lic" on net+or" tree node, 'n ri#ht hand side you +ill #et text box for enterin# port no.
6. .han#e port number +ith desire one.
&. clic" on restart button.
$10 !an 7 send multi"le res"onses ,or a sin8le request?
9o. 3hat doesn%t even ma"e sense 0$
Cou can, ho+ever, send a =redirect=, +hich tells the user%s bro+ser to send another re)uest, possibly
to the same servlet +ith different parameters. <earch this BAE on =redirect= to learn more.
$20 What is 5B4; based lo8in and how do 7 use it? Also1 what servlet containers su""ort it?
Borm based lo#in is one of the four "no+n +eb based lo#in mechanisms. Bor completeness I list all of
them +ith a description of their nature
1. CII( -asic Authentication
o An authentication protocol defined +ithin the 233/ protocol !and based on headers$. It
indicates the 233/ realm for +hich access is bein# ne#otiated and sends pass+ords
+ith base64 encodin#, therefore it is not very secure. !<ee 1B.2J6N for more
information.$
2. CII( ,i/est Authentication
o Hi"e 233/ ?asic Authentication, but +ith the pass+ord transmitted in an encrypted
form. It is more secure than ?asic, but less then 233/< Authentication +hich uses
private "eys. Cet it is not currently in +idespread use.
0. CII(" Authentication 1""# )utual Authentication2
o 3his security mechanism provides end user authentication usin# 233/< !233/ over
<<H$. It performs mutual !client Q server$ certificate based authentication +ith a set of
different cipher suites.
3. Gor* -ased #o/in
o A standard 235H form !static, <ervlet7*</ or script #enerated$ for lo##in# in. It can be
associated +ith protection or user domains, and is used to authenticate previously
unauthenticated users.
o 3he ma(or advanta#e is that the loo" and feel of the lo#in screen can be controlled !in
comparison to the 233/ bro+sers% built in mechanisms$.
3o support 1., 3., and 4. of these authentication mechanisms is a re)uirement of the *2--
<pecification !as of v1.2, 3.4.1.3 1e)uired Ho#in 5echanisms$. !233/ Di#est Authentication is not a
re)uirement, but containers are encoura#ed to support it.$
8ou can also see section 9696::6: of the J;77 Specs6 (<ser "uthentication4 =e Client) for more
detailed descriptions of the mechanisms6
3hus any <ervlet container that conforms to the *2-- /latform specification should support form based
lo#in.
3o be more specific, the <ervlet 2.2 <pecification describes7specifies the same mechanisms in 11.5
includin# form based lo#in in 11.5.3.
,his section (::6>69) descries in depth the nature4 the re0uirements and the naming conventions of
form ased login and I suggest to take a look at it6
2ere is a sample of a conformin# 235H lo#in form
\form methodT=/'<3= actionT=(XsecurityXchec"=M
\input typeT=text= nameT=(Xusername=M
\input typeT=pass+ord= nameT=(Xpass+ord=M
\7formM
Ino+n <ervlet containers that support B'150based lo#in are
i/lanet Application <erver
3omcat !the reference implementation of the *ava <ervlet A/I$
$30 How do 7 ca"ture a request and dis"atch the exact request .with all the "arameters
received0 to another 24+?
As far as i "no+ it depends on the location of the next tar#et url.
If the next servlet url is in the same host, then you can use the for+ard method.
2ere is an example code about usin# for+ard
1e)uestDispatcher rd T null:
<trin# tar#et41H T =tar#etXservletXname=:
<ervlet.ontext ctx T this.#et<ervlet.ontext!$:
rd T ctx.#et1e)uestDispatcher!tar#et41H$:
rd.for+ard!re)uest, response$:
$#0 How can the data within an H<;+ ,orm be re,reshed automatically whenever there is a
chan8e in the database?
*</ is intended for dynamically #eneratin# pa#es. 3he #enerated pa#es can include +ml, html, dhtml
or +hatever you +ant...
>hen you have a #enerated pa#e, *</ has already made its +or". Brom this moment you have a
pa#e.
If you +ant automatic refreshin#, then this should be acomplished by the technolo#y included in the
#enerated pa#e !*</ +ill tell only +hat to include in the pa#e$.
3he bro+ser can not be loaded by extern factors. 3he bro+ser is the one +ho fetches url%s since
the http protocol is re)uest0response based. If a server can reload a bro+ser +ithout its allo+, it
implies that +e could be receivin# pa#es +hich +e haven%t as"ed for from servers.
5ay you could use applets and a <erver<oc"et for receivin# incomin# si#nals from the server for
chan#ed data in the D?. 3his +ay you can load ne+ information inside the applet or try to force a
pa#e reload.
R3hat%s a nice idea 00 it could use the sho+Document!$ call to reload the current pa#e. It could also
use 233/ pollin# instead of maintainin# an expensive soc"et connection. 0AlexS
/erhaps !if possible$, could be simpler usin# an automatic *ava<cript refreshin# function that force
pa#e reload after a specified time interval.
$$0 What is a web a""lication .or ?weba""?0?
A +eb application is a collection of servlets, html pa#es, classes, and other resources that can be
bundled and run on multiple containers from multiple vendors. A +eb application is rooted at a specific
path +ithin a +eb server. Bor example, a catalo# application could be located at
http77+++.mycorp.com7catalo#. All re)uests that start +ith this prefix +ill be routed to the
<ervlet.ontext +hich represents the catalo# application.
$%0 How can 7 call a servlet ,rom a J)= "a8e? How can 7 "ass variables ,rom the J)= that
the servlet can access?
Cou can use \(spfor+ard pa#eT=7relativepath7Cour<ervlet= 7M or
response.send1edirect!=http77path7Cour<ervlet=$.
Lariables can be sent as
\(spfor+ard pa#eT7relativepath7Cour<ervletM
\(spparam nameT=name1= valueT=value1= 7M
\(spparam nameT=name2= valueT=value2= 7M
\7(spfor+ardM
Cou may also pass parameters to your servlet by specifyin#
response.send1edirect!=http77path7Cour<ervletGparam1Tval1=$.
$'0 !an there be more than one instance o, a servlet at one time ?
It is important to note that there can e more than one instance of a given Servlet class in the servlet
container6 %or e5ample4 this can occur &here there &as more than one servlet definition that utili?ed a
specific servlet class &ith different initiali?ation parameters6 ,his can also occur &hen a servlet
implements the Single,hread*odel interface and the container creates a pool of servlet instances to
use6
$(0 How can 7 measure the ,ile downloadin8 time usin8 servlets?
<ervlet'utput<tream out T response.#et'utput<tream!$:
<trin# filename T #et<ervlet.ontext!$.#et1eal/ath!re)uest.#etEuery<trin#!$$:
BileInput<tream fin T ne+ BileInput<tream!filename$:
lon# start T <ystem.current3ime5illis!$:
byte dataRS T ne+ byteR1J24S:
int len T J:
+hile !!len T fin.read!data$$ M J$ 6
out.+rite!data, J, len$:
;
out.flush!$:
lon# stop T <ystem.current3ime5ills!$:
lo#!=too" = @ !stop 0 start$ @ =ms to do+nload = @ filename$:

$90 What is inter6servlet communication?
As the name says it, it is communication bet+een servlets. <ervlets tal"in# to each other. R3here are
many +ays to communicate bet+een servlets, includin#
1e)uest Dispatchin#
233/ 1edirect
<ervlet .hainin#
233/ re)uest !usin# soc"ets or the 41H.onnection class$
<hared session, re)uest, or application ob(ects !beans$
Direct method invocation !deprecated$
<hared static or instance variables !deprecated$
<earch the BAE, especially topic 5essa#e /assin# !includin# 1e)uest Dispatchin#$ for information on
each of these techni)ues. 0AlexS
?asically inter<ervlet communication is acheived throu#h servlet chainin#. >hich is a process in +hich
you pass the output of one servlet as the input to other. 3hese servlets should be runnin# in the same
server.
e.#. <ervlet.ontext.#et1e)uestDispatcher!2ttp1e)uest, 2ttp1esponse$.for+ard!=9ext<ervlet=$ : Cou
can pass in the current re)uest and response ob(ect from the latest form submission to the next
servlet7*</. Cou can modify these ob(ects and pass them so that the next servlet7*</ can use the
results of this servlet.
3here are some <ervlet en#ine specific confi#urations for servlet chainin#.
<ervlets can also call public functions of other servlets runnin# in the same server. 3his can be done
by obtainin# a handle to the desired servlet throu#h the <ervlet.ontext 'b(ect by passin# it the
servlet name ! this ob(ect can return any servlets runnin# in the server$. And then callin# the function
on the returned <ervlet ob(ect.
e.#. 3est<ervlet testT !3est<ervlet$#et<ervlet.onfi#!$.#et<ervlet.ontext!$.#et<ervlet!='ther<ervlet=$:
other<ervletDetailsT 3est.#et<ervletDetails!$:
Cou must be careful +hen you call another servlet%s methods. If the servlet that you +ant to call
implements the <in#le3hread5odel interface, your call could conflict +ith the servlet%s sin#le threaded
nature. !3he server cannot intervene and ma"e sure your call happens +hen the servlet is not
interactin# +ith another client.$ In this case, your servlet should ma"e an 233/ re)uest to the other
servlet instead of direct calls.
<ervlets could also invo"e other servlets pro#rammatically by sendin# an 233/ re)uest. 3his could be
done by openin# a 41H connection to the desired <ervlet.
%-0 How do 7 ma:e servlet aliasin8 wor: with A"acheG<omcat?
>hen you use 3omcat standalone as your +eb server, you can modify the +eb.xml in
W3'5.A3X2'5-7+ebapps7myApp7>-?0I9B to add a url0pattern
\+eb0appM
\servletM
\servlet0nameM
my<ervlet
\7servlet0nameM
\servlet0classM
my<ervlet
\7servlet0classM
\7servletM
\servlet0mappin#M
\servlet0nameM
my<ervlet
\7servlet0nameM
\url0patternM
7(sp0bin78
\7url0patternM
\7servlet0mappin#M
\7+eb0appM
3his +ill let you use http77+ebserverNJNJ7myApp7(sp0bin7stuff.html instead of
http77+ebserverNJNJ7myApp7servlet7my<ervlet7stuff.html ?ut it +on%t +or" on port NJ if you%ve
inte#rated 3omcat +ith Apache. Oraeme >allace provided this tric" to remedy the situation. Add the
follo+in# to your tomcat0apache.conf !or to a static version of it, since tomcat re0#enerates the conf
file every time it starts$
\Hocation5atch 7myApp7(sp0bin78
<et2andler (serv0servlet
\7Hocation5atch
3his lets Apache turn over handlin# of the url pattern to your servlet.
%10 7s there any way to determine the number o, concurrent connections my servlet en8ine
can handle?
Depends on +hether or not your servlet container uses thread poolin#. If you do not use a thread
pool, the number of concurrent connections accepted by 3omcat 3.1, for example, is 1J. 3his you can
see for yourself by testin# a servlet +ith the Apache *5eter tool.
2o+ever, if your servlet container uses a thread pool, you can specify the number of concurrent
connections to be accepted by the container. Bor 3omcat 3.1, the information on ho+ to do so is
supplied +ith the documentation in the 3'5.A3X2'5-7doc7u#uide directory.
%20 What is a request dis"atcher and how does it wor:?
A 1e)uestDispatcher ob(ect can for+ard a client%s re)uest to a resource or include the resource itself
in the response bac" to the client. A resource can be another servlet, or an 235H file, or a *</ file,
etc.
Cou can also thin" of a 1e)uestDispatcher ob(ect as a +rapper for the resource located at a #iven path
that is supplied as an ar#ument to the #et1e)uestDispatcher method.
Bor constructin# a 1e)uestDispatcher ob(ect, you can use either the
<ervlet1e)uest.#et1e)uestDispatcher!$ method or the <ervlet.ontext.#et1e)uestDispatcher!$
method. 3hey both do the same thin#, but impose sli#htly different constraints on the ar#ument path.
Bor the former, it loo"s for the resource in the same +ebapp to +hich the invo"in# servlet belon#s and
the pathname specified can be relative to invo"in# servlet. Bor the latter, the pathname must be#in
+ith %7% and is interpreted relative to the root of the +ebapp.
3o illustrate, suppose you +ant <ervletXA to invo"e <ervletX?. If they are both in the same directory,
you could accomplish this by incorporatin# the follo+in# code fra#ment in either the service method or
the doOet method of <ervletXA

1e)uestDispatcher dispatcher T #et1e)uestDispatcher!=<ervletX?=$:
dispatcher.for+ard! re)uest, response $:
+here re)uest, of type 2ttp<ervlet1e)uest, is the first parameter of the enclosin# service method !or
the doOet method$ and response, of type 2ttp<ervlet1esponse, the second. Cou could accomplish the
same by

1e)uestDispatcher
dispatcherT#et<ervlet.ontext!$.#et1e)uestDispatcher! =7servlet7<ervletX?= $:
dispatcher.for+ard! re)uest, response $:
%30 What is a )ervlet !ontext?
A <ervlet .ontext is a #roupin# under +hich related servlets !and *</s and other +eb resources$ run.
3hey can share data, 41H namespace, and other resources. 3here can be multiple contexts in a
sin#le servlet container.
3he <ervlet.ontext ob(ect is used by an individual servlet to =call bac"= and obtain services from the
container !such as a re)uest dispatcher$. 1ead the *avaDoc for (avax.servlet.<ervlet.ontext for more
information.
Cou can maintain =application #lobal= variables by usin# <ervlet .ontext Attributes.
%#0 Does the 4equestDis"atcher ex"ect a relative 24+ to be relative to the ori8inally6called
servlet or to the current servlet .i, di,,erent0?
<ince the 1e)uestDispatcher +ill be passin# the control !re)uest ob(ect and response ob(ect$ from the
current <ervlet, the relative 41H must be relative to the current servlet.
3he ori#inally called servlet has passed the control to the current servlet, and no+ current servlet is
actin# as controller to other resourses.
%$0 What is the di,,erence between in6"rocess and out6o,6"rocess servlet containers?
3he in0process <ervlet containers are the containers +hich +or" inside the *L5 of >eb server, these
provides #ood performance but poor in scalibility.
3he out0of0process containers are the containers +hich +or" in the *L5 outside the +eb server. poor
in performance but better in scalibility
In the case of out0of0process containers, +eb server and container tal"s +ith each other by usin# the
some standard mechanism li"e I/..
In addition to these types of containers, there is 3rd type +hich is stand0alone servlet containers.
3hese are an inte#ral part of the +eb server.
%%0 How is )in8le<hread;odel im"lemented in <omcat? 7n other containers? H7 would
assume that <omcat uses its connection thread "ool1 and creates a new instance o,
the servlet ,or each connection thread1 instead o, sharin8 one instance amon8 all
threads3 7s that true?I
3he )uestion mixes to#ether t+o rather independent aspects of a servlet container =concurrency
control= and =thread poolin#=.
.oncurrency control, such as achieved by havin# a servlet implement the <in#le3hread5odel interface,
addresses the issue of thread safety. A servlet +ill be thread0safe or thread0unsafe re#ardless of
+hether the servlet container used a thread pool. 3hread poolin# merely eliminates the overhead
associated +ith the creation and destruction of threads as a servlet container tries to respond to
multiple re)uests received simultaneously. It is for this reason that the specification document for
<ervlet 2.2 A/I is silent on the sub(ect of thread poolin# 00 as it is merely an implementation detail.
2o+ever, the document does indeed address the issue of thread safety and ho+ and +hen to use
<in#le3hread5odel servlets.
<ection 3.3.3.1 of the <ervlet 2.2 A/I <pecification document says that if a servlet implements the
<in#le3hread5odel it is #uaranteed =that only one re)uest thread at time +ill be allo+ed in the service
method.= It says further that =a servlet container may satisfy this #uarantee by serialiFin# re)uests on
a servlet or by maintainin# a pool of servlet instances.=
'bviously, for superior performance you%d +ant the servlet container to create multiple instances of a
<in#le3hread5odel type servlet should there be many re)uests received in )uic" succession. >hether
or not a servlet container does that depends completely on the implementation. 5y experiments sho+
that 3omcat 3.1 does indeed create multiple instances of a <in#le3hread5odel servlet, but only for the
first batch of re)uests received concurrently. Bor subse)uent batches of concurrent re)uests, it seems
to use only one of those instances.
%'0 Which servlet containers have "ersistent session su""ort? )"eci,ically1 does <omcat
331?
All servlet containers that implement the <ervlet 2.2 A/I must provide for session trac"in# throu#h
either the use of coo"ies or throu#h 41H re+ritin#. All 3omcat servlet containers support session
trac"in#.
%(0 !an 7 use JAA) as the authentication technolo8y ,or servlets ?
Ces, *AA< can be used as authentication technolo#y for servlets. 'ne important feature of *AA< is
pure *ava implementation. 3he *AA< infrastructure is divided into t+o main components an
authentication component and an authoriFation component. 3he *AA< authentication component
provides the ability to reliably and securely determine +ho is currently executin# *ava code,
re#ardless of +hether the code is runnin# as an application, an applet, a bean, or a servlet.
%90 How can 7 set a servlet to load on startu" o, the container1 rather than on the ,irst
request?
3he <ervlet 2.2 spec defines a load0on0startup element for (ust this purpose. /ut it in the \servletM
section of your +eb.xml deployment descriptor. It is either empty !\load0on0startup7M$ or contains =a
positive inte#er indicatin# the order in +hich the servlet should be loaded. Ho+er inte#ers are loaded
before hi#her inte#ers. If no value is specified, or if the value specified is not a positive inte#er, the
container is free to load it at any time in the startup se)uence.=
Bor example,
\servletM
\servlet0nameMfoo\7servlet0nameM
\servlet0classMcom.foo.servlets.Boo\7servlet0classM
\load0on0startupM5\7load0on0startupM
\7servletM
<ome servlet containers also have their o+n techni)ues for confi#urin# this: please submit feedbac"
+ith information on these.
'-0 7s it "ossible to write a servlet that acts as a 5<= server?
Ces. It +ould spa+n a thread that opens a <erver<oc"et, then listens for incomin# connections and
spea"s the B3/ protocol.
'10 7s there a way to disable a userCs ability to double6clic: a submit ima8eEbutton .and
there,ore submittin8 du"licate data 66 multi"le submits0? 7s there a way to do this
with Javascri"t?
Oive the submit ima#e !or button$ an on.lic"!$ handler. 2ave the handler chec" if a fla# is set and if
not set the fla# and submit the form and then clear the form.
'20 What are the main di,,erences between )ervlets and 7)A=7?
3he first difference is obviously that <ervlets is the technolo#y from <un 5icrosystems and I<A/I is
from 5icrosoft.
%ther ,ifferences are
i. <ervlet is a simple .class file and I<A/I is a DHH
ii. <ervlets run in the <ervlet containers and may be in0process or out of process. I<As run in the
same address space as the 233/ server
iii. <ervlet container preprocesses and postprocesses the data communication bet+een the client
and server. I<A/I Bilters provide the capability of pre0processin# and post0processin# of all
data sent bet+een the client and the server
iv. *ava is the only choice for +ritin# <ervlets, L.@@75B. is used to +rite I<A/I code
v. <ervlets +or"s on most of the >eb servers plus third party containers can be inte#rated +ith
other +eb servers to provide servlets on them. I<A/I +or"s on only I<A/I0compliant >eb
server !for example, 5icrosoft Internet Information <erver$
vi. <ervlets can connect to the Databases throu#h *D?. as +ell as (dbc0odbc brid#es. I<A/I can
connect to Databases throu#h only 'D?.
vii. <ervlets have access to many server0side technolo#ies li"e -*? and etc. I<A/I is limited in
scope
viii. 5ultiple commands can be implemented in a servlet by usin# pathinfo. I<A/I allo+s multiple
commands in one DHH, implemented as member functions of the CCttp"erver object in the
DHH.
ix. .ontent #eneration and content presentation can be done seperately in <ervlets +ith the help
of *</. I<A/I code has to #enerate 235H code itself.
'30 !an 7 associate a servlet with a "articular mime6ty"e1 so i, the client requests a ,ile o,
that ty"e1 my servlet will be executed?
In +eb.xml you can use a mime0mappin# to map the type +ith a certain extension and then map the
servlet to that extension.
e.#.
\mime0mappin#M
\extensionM
FFF
\7extensionM
\mime0typeM
text7plain
\7mime0typeM
\7mime0mappin#M
\servlet0mappin#M
\urlM
8.FFF
\7urlM
\servlet0nameM
5y<ervlet
\7servlet0nameM
\7servlet0mappin#M
<o, +hen a file for type FFF is re)uested, the servlet #ets called.
'#0 What are the di,,erent cases ,or usin8 send4edirect.0 vs3 8et4equestDis"atcher.0?
>hen you +ant to preserve the current re)uest7response ob(ects and transfer them to another
resource >I32I9 the context, you must use #et1e)uestDispatcher or #et9amedDispatcher.
If you +ant to dispatch to resources '43<ID- the context, then you must use send1edirect. In this
case you +on%t be sendin# the ori#inal re)uest7response ob(ects, but you +ill be sendin# a header
as"in# to the bro+ser to issue a re)uest to the ne+ 41H.
If you don%t need to preserve the re)uest7response ob(ects, you can use either.
'$0 How do 7 access the value o, a coo:ie usin8 Java)cri"t?
Cou can manipulate coo"ies in *ava<cript +ith the document.coo"ie property. Cou can set a coo"ie by
assi#nin# this property, and retrieve one by readin# its current value.
3he follo+in# statement, for example, sets a ne+ coo"ie +ith a minimum number of attributes
document.coo"ie T =coo"ie9ameTcoo"ieLalue=:
And the follo+in# statement displays the property%s value
alert!document.coo"ie$:
3he value of document.coo"ie is a strin# containin# a list of all coo"ies that are associated
+ith a +eb pa#e. It consists, that is, of nameTvalue pairs for each coo"ie that matches the
current domain, path, and date. 3he value of the document.coo"ie property, for instance,
mi#ht be the follo+in# strin#
coo"ie9ame1Tcoo"ieLalue1: coo"ie9ame2Tcoo"ieLalue2:
'%0 How do 7 write to a lo8 ,ile usin8 J)= under <omcat? !an 7 ma:e use o, the lo8.0
method ,or this?
Ces, you can use the <ervlet A/I%s lo# method in 3omcat from +ithin *</s or servlets. 3hese messa#es
are stored in the server%s lo# directory in a file called servlet.lo#.
''0 How can 7 use a servlet to "rint a ,ile on a "rinter attached to the client?
3he security in a bro+ser is desi#ned to restrict you from automatin# thin#s li"e this. 2o+ever, you
can use *ava<cript in the 235H your servlet returns to print a frame. 3he bro+ser +ill still confirm the
print (ob +ith the user, so you can%t completely automate this. Also, you%ll be printin# +hatever the
bro+ser is displayin# !it +ill not reliably print plu#0ins or applets$, so normally you are restricted to
235H and ima#es.
R3he *ava<cript source code for doin# this is
\input typeT=button= on.lic"T=+indo+.print!J$= valueT=/rint 3his /a#e=M
'(0 How do you do servlet aliasin8 with A"ache and <omcat?
<ervlet aliasin# is a t+o part process +ith Apache and 3omcat. Birst, you must map the re)uest in
Apache to 3omcat +ith the Ap*<erv5ount directive, e.#.,
Ap6"erv)ountB*+servletB:%%I
<econd, you must map that url pattern to a servlet name and then to a servlet class in your
+eb.xml confi#uration file. 2ere is a sample exerpt
\servletM
\servlet0nameMmyservlet\7servlet0nameM
\servlet0classMcom.mypac"a#e.5y<ervlet\7servlet0classM
\7servletM
\servlet0mappin#M
\servlet0nameMmyservlet\7servlet0nameM
\url0patternM7myservlet\7url0patternM
\7servlet0mappin#M
'90 7 want my servlet "a8e to redirect to a lo8in "a8e i, the session has timed out3 How can
7 :now i, my session has timed out?
If the servlet en#ine does the time0out, follo+in# code should help you
77assume you have a 2ttp<ervlet1e)uest re)uest
if!re)uest.#et<ession!false$TTnull$ 6
77no valid session !timeoutedTinvalid$
77code to redirect to lo#in pa#e
;
(-0 !an <omcat be con,i8ured to inter"ret all1 or selected1 3html ,iles within a 8iven context
as J)=? Br1 do J)= ,iles have to end with a 3&s" extension?
yes you can do that by modifyin# the +eb.xml file. Cou +ill have to invo"e the
or#.apache.(asper.runtime.*sp<ervlet for all the re)uests havin# extension .html. Cou can do that by
chan#in# the <ervlet mappin# code
\servlet0mappin#M
\servlet0nameM
(sp
\7servlet0nameM
\urlM8.html\7urlM
\7servlet0mappin#M
And comment out the follo+in# bloc"
\mime0mappin#M
\extensionM
html
\7extensionM
\mime0typeM
text7html
\7mime0typeM
\7mime0mappin#M
(10 What is the di,,erence between request attributes1 session attributes1 and
)ervlet!ontext attributes?
A <ervlet.ontext attribute is an ob(ect bound into a context throu#h <ervlet.ontext.setAttribute!$
method and +hich is available to AHH servlets !thus *</$ in that context, or to other contexts via the
#et.ontext!$ method. ?y definition a context attribute exists locally in the L5 +here they +ere
defined. <o, they%re unavailable on distributed applications.
<ession attributes are bound to a session, as a mean to provide state to a set of related 233/
re)uests. <ession attributes are available '9HC to those servlets +hich (oin the session. 3hey%re also
unavailable to different *L5s in distributed scenarios. 'b(ects can be notified +hen they%re
bound7unbound to the session implementin# the 2ttp<ession?indin#Histener interface.
1e)uest attributes are bound to a specific re)uest ob(ect, and they last as far as the re)uest is
resolved or +hile it "eep dispatched from servlet to servlet. 3hey%re used more as comunication
channel bet+een <ervlets via the 1e)uestDispatcher Interface !since you can%t add /arameters...$ and
by the container. 1e)uest attributes are very useful in +eb apps +hen you must provide setup
information bet+een information providers and the information presentation layer !a *</$ that is
bound to a specific re)uest and need not be available any lon#er, +hich usually happens +ith sessions
+ithout a ri#orous control strate#y.
3hus +e can say that context attributes are meant for infra0structure such as shared connection pools,
session attributes to contextual information such as user identification, and re)uest attributes are
meant to specific re)uest info such as )uery results.
(20 Are sin8letonEstatic ob&ects shared between servlet contexts?
REuestion continues Bor example if I have t+o contexts on a sin#le +eb server, and each context
uses a lo#in servlet and the lo#in servlet connects to a D?. 3he D? connection is mana#ed by a
sin#leton ob(ect. Do both contexts have their o+n instance of the D? sin#leton or does one instance
#et shared bet+een the t+oGS
It depends on from +here the class is loaded.
3he classes loaded from context%s >-?0I9B directory are not shared by other contexts, +hereas
classes loaded from .HA<</A32 are shared. <o if you have exactly the same D?.onnection class in
>-?0I9B7classes directory of t+o different contexts, each context #ets its o+n copy of the sin#leton
!static$ ob(ect.
(30 When buildin8 web a""lications1 what are some areas where synchroniDation "roblems
arrise?
In #eneral, you +ill run into synchroniFation issues +hen you try to access any shared resource. ?y
shared resource, I mean anythin# +hich mi#ht be used by more than one re)uest.
3ypical examples include
.onnections to external servers, especially if you have any sort of poolin#.
Anythin# +hich you include in a 2ttp<ession. !Cour user could open many bro+ser +indo+s
and ma"e many simultaneous re)uests +ithin the one session.$
Ho# destinations, if you do your o+n lo##in# from your servlets.
(#0 What is the di,,erence between a"ache webserver1 &ava webserver and tomcat server?
Apache is an 233/ server +ritten in . that can be compiled and run on many platforms.
*ava >eb<erver is an 233/ server from <un +ritten in *ava that also supports <ervlets and *</.
3omcat is an open0source 233/ server from the Apache Boundation, +ritten in *ava, that supports
<ervlets and *</. It can also be used as a =plu#0in= to native0code 233/ servers, such as Apache >eb
<erver and II<, to provide support for <ervlets !+hile still servin# normal 233/ re)uests from the
primary, native0code +eb server$.
($0 How can you embed a Java)cri"t within servlets E J)= "a8es?
Cou don%t have to do anythin# special to include *ava<cript in servlets or *</ pa#es. *ust have the
servlet7*</ pa#e #enerate the necessary *ava<cript code, (ust li"e you +ould include it in a ra+ 235H
pa#e.
3he "ey thin# to remember is it +on%t run in the server. It +ill run bac" on the client +hen the
bro+ser loads the #enerate 235H, +ith the included *ava<cript.
(%0 How can 7 ma:e a =B)< request throu8h res"onse3send4edirect.0 or
res"onse3set)tatus.0 and res"onse3setHeader.0 methods?
Cou can%t. It%s a fundamental limitation of the 233/ protocol. Cou%ll have to fi#ure out some other +ay
to pass the data, such as
4se O-3 instead
5a"e the /'<3 from your servlet, not from the client
<tore data in coo"ies instead of passin# it via O-37/'<3
('0 How do 7 "ass a request ob&ect o, one servlet as a request ob&ect to another servlet?
4se a 1e)uest Dispatcher.
((0 7 call a servlet as the action in a ,orm1 ,rom a &s"3 How can 7 redirect the res"onse ,rom
the servlet1 bac: to the J)=? .4equestDis"atcher3,orward will not hel" in this case1 as
7 do not :now which resource has made the request3 request38et4equest247 will
return the uri as contained in the action ta8 o, the ,orm1 which is not what is needed30
Cou%ll have to pass the *</%s 41I in to the servlet, and have the servlet call send1edirect to #o bac" to
the *</. Bor example
\B'15 A.3I'9T=7foo7myservlet=M
\I9/43 3C/-T=2IDD-9= 9A5-T=redirect= LAH4-T=7foo7this(sp.(sp=M
<hoe siFe \I9/43 9A5-T=shoesiFe=M
\I9/43 3C/-T=<4?5I3=M
\7B'15M
3hen in the servlet...
response.send1edirect!re)uest.#et/arameter!=redirect=$$:
(90 What is the )ervlet!on,i8 ob&ect1 and why is it use,ul?
3he <ervlet.onfi# ob(ect is an interface. It contains the methods
#etInit/arameter
#etInit/arameter9ames
#et<ervlet.ontext
#et<ervlet9ame
Cou can use the methods to determine the <ervlet%s initialiFation parameters, the name of the servlets
instance, and a reference to the <ervlet .ontext the servlet is runnin# in.
#et<ervlet.ontext is the most valuable method, as it allo+s you to share information accross
an application !context$.
9-0 7 have a 8lobal variable in a servlet class3 What will ha""en to this 8lobal variable i,
two requests hit on the same time?
>hat +ill happen is an unforeseeable event.
3he best +ay to establish a default occurrence !the servlet handles a re)uest at a time$ is
to s+nchroni=e the access to the #lobal variable or alternatively to create a servlet that implements
the "in/leIhread)odel interface.
910 )u""ose 7 have 2 servers1 server1 and server23 How can 7 ta:e data in a coo:ie ,rom
server11 and send it to server2?
Cou%ll have to create a !ne+$ similar coo"ie on server 2.
2ave a :eadCookie"ervlet runnin# on server1 that
1eads the coo"ie, usin# reDuest./etCookies12
1edirects to WriteCookie"ervlet runnin# on server2, passin# the coo"ie name, value and
expiration date as re)uest parameters, usin# response.send:edirect12.
2ave a WriteCookie"ervlet runnin# on server2 that
1eads the coo"ie name, value and expiration date re)uest parameters,
usin# reDuest./et(ara*eter12.
.reates a similar coo"ie, usin# response.addCookie12.
920 How can 7 "ass data ,rom a servlet runnin8 in one context .weba""0 to a servlet
runnin8 in another context?
3here are three +ays I can thin" of off the top of my head
1. <tore the information you +ant to share in a persistant format, such as in a file system or
database. 3hat +ay, any servlet that is runnin# in a *L5 that can =see= these resources can
#et to this information.
2. If persistin# this information is not an option, you can bind this information to a context that is
accessible to all servlet contexts, such as the application server%s context. 3his +ay, you can
"eep the data you +ant to share in memory.
3. 4se the old fashion +ay of passin# information to a servlet 0 233/. 'ne servlet could fo+ard a
re)uest to another servlet and include the data that needs to be shared as parameters in the
re)uest.
930 How can 7 write an ?error "a8e? 66 that is1 a servlet or J)= to re"ort errors o, other
servlets?
3he <ervlet 2.2 specification allo+s you to specify an error pa#e !a servlet or a *</$ for different "inds
of 233/ errors or <ervlet-xceptions. Cou can specify this in deployment descriptor of the +eb
application as
\error0pa#eM
\exception0typeMBoo-xception\7exception0typeM
\locationM7error.(sp\7locationM
\7error0pa#eM
+here Boo-xception is a subclass of <ervlet-xception.
3he +eb container invo"es this servlet in case of errors, and you can access the follo+in# information
from the re)uest ob(ect of error servlet7*</ error code, exception type, and a messa#e.
9#0 What is the di,,erence between )ervlet!ontext and )ervlet!on,i8?
A <ervlet.ontext represents the context in a servlet container of a servlet instance operates. A servlet
container can have several contexts !or +eb applications$ at one time. -ach servlet instance is runnin#
in one of these contexts. All servlets instances runnin# in the same context are part of the same +eb
application and, therefore, share common resources. A servlet accesses these shared resource !such
as a 1e)uestDispatcher and application properties$ throu#h the <ervlet.ontext ob(ect.
3his notion of a +eb application became very si#nificant upon the <ervlet 2.1 A/I, +here you could
deploy an entire +eb application in a >A1 file. 9otice that I al+ays said =servlet instance=, not servlet.
3hat is because the same servlet can be used in several +eb applications at one time. In fact, this
may be common if there is a #eneric controller servlet that can be confi#ured at run time for a specific
application. 3hen, you +ould have several instances of the same servlet runnin#, each possibly havin#
different confi#urations.
3his is +here the <ervlet.onfi# comes in. 3his ob(ect defines ho+ a servlet is to be confi#ured is
passed to a servlet in its init method. 5ost servlet containers provide a +ay to confi#ure a servlet at
run0time !usually throu#h flat file$ and set up its initial parameters. 3he container, in turn, passes
these parameters to the servlet via the <ervet.onfi#.
9$0 2nder what circumstances will a servlet be reloaded?
3hat depends on the <ervlet container.
5ost of the <ervlet containers reload the servlet only it detects the code chan#e in the <ervlet, not in
the referenced classes.
In 3omcat%s server.xml deployment descriptor, if you have mentioned
\.ontext pathT=7myApp=
doc?aseT=D7myApp7+ebDev=
cross.ontextT=true=
debu#T=J=
reloadableKLtrueL
trustedT=false= M
\7.ontextM
3he reloadable K true ma"es the ma#ic. -very time the <ervlet container detects that the <ervlet
code is chan#ed, it +ill call the destroy on the currently loaded <ervlet and reload the ne+ code.
?ut if the class that is referenced by the <ervlet chan#es, then the <ervlet +ill not #et loaded. Cou +ill
have to chan#e the timestamp of the servlet or stop0start the server to have the ne+ class in the
container memory.
9%0 What is a )ervlet 5ilter?
A filter is basically a component that is invo"ed +henever a resource is invo"ed for +hich the filter is
mapped. 3he resource can be somethin# li"e a servlet, or a 41H pattern. A filter normally +or"s on
the re)uest, response, or header attributes, and does not itself send a response to the client.
9'0 7 am usin8 the 4equestDis"atcherCs ,orward.0 method to redirect to a J)=3 <he "roblem
is that the &s"Cs url is now relative to the servletCs url and all my urlCs in the &s" such
as Jim8 srcK?"ic38i,?L will be corru"t3 How do 7 solve this "roblem?
Cou can use absolute urls li"e
\?'DCM
\Y <trin# base T re)uest.#et.ontext/ath!$: YM
\I5O srcT=\YTbaseYM7im#7pic.#if=M
\7?'DCM
or +rite out a ?A<- ta# li"e
\Y <trin# base T re)uest.#et.ontext/ath!$: YM
\2-ADM
\?A<- 21-BT=\YTbaseYM=M
\72-ADM
\?'DCM
\I5O srcT=im#7pic.#if=M
\7?'DCM
3hat should ta"e care of the problem.
9(0 How can 7 return a readily available .static0 H<;+ "a8e to the user instead o,
8eneratin8 it in the servlet?
3o solve your problem, you can either send a =1edirect= bac" to the client or use a 1e)uestDispatcher
and for+ard your re)uest to another pa#e
1. 1edirect
A redirection is made usin# the 2ttp<ervlet1esponse ob(ect
if!condition$ 6
response.send1edirect!=pa#e1.html=$:
; else 6
response.send1edirect!=pa#e2.html=$:
;
2. 1e)uestDispatcher
A re)uest dispatcher can be obtained throu#h the <ervlet.ontext. It can be used to include
another pa#e or to for+ard to it.
if!condition$ 6
this.#et<ervlet.ontext!$
.#et1e)uestDispatcher!=pa#e1.html=$.for+ard!$:
; else 6
this.#et<ervlet.ontext!$
.#et1e)uestDispatcher!=pa#e2.html=$.for+ard!$:
;
?oth solutions re)uire, that the pa#es are available in you document root. If they are located
some+here else on your filesystem, you have to open the file manually and copy their content to the
output +riter.
If your application server is set up in combination +ith a normal +eb server li"e Apache, you should
use solution !1$, because the the +eb server usually serves static files much faster than the
application server.
990 What is the di,,erence between static variables and instance variables in a servlet?
Accordin# to the *ava Han#ua#e definition, a static variable is shared amon# all instances of a class,
+here a non0static variable 00 also called an instance variable 00 is specific to a sin#le instance of that
class.
Accordin# to the <ervlet specification, a servlet that does not declare <in#le3hread5odel usually has
one and only one instance, shared amon# all concurrent re)uests hittin# that servlet.
3hat means that, in servlets !and other multithreaded applications$, an instance variable behaves very
much li"e a static variable, since it is shared amon# all threads. Cou have to be very careful about
synchroniFin# access to shared data.
3he bi# difference bet+een instance variables and static variables comes +hen you have confi#ured
your servlet en#ine to instantiate t+o instances of the same servlet class, but +ith different init
parameters. In this case, there +ill be t+o instances of the same servlet class, +hich means t+o sets
of instance variables, but only one set of static variables.
1emember that you can store data in lots of different places in a servlet. 3o +it
#ocal variables J for loop iterators, result sets, and so forth
:eDuest attributes J for data that must be passed to other servlets invo"ed +ith the
1e)uestDispatcher
"ession attributes J persists for all future re)uests from the current user only
Instance variables J for data that persists for the life of the servlet, shared +ith all
concurrent users
"tatic variables J for data that persists for the life of the application, shared +ith all
concurrent users 00 includin# any other servlet instances that +ere instantiated +ith different
init parameters
Context attributes J for data that must persist for the life of the application, and be shared
+ith all other servlets
1--0 How can 7 share data between two di,,erent web a""lications?
Different servlets may share data +ithin one application via <ervlet.ontext. If you have a compellin#
to put the servlets in different applications, you may +anna consider usin# -*?s.

You might also like