Sie sind auf Seite 1von 29


Q1: What are the advantages of OOPL?

Ans: Object oriented programming languages directly represent the real life
objects. The features of OOPL as inhreitance, polymorphism, encapsulation makes
it powerful.
Q2: What do mean ! "o#!mor"h$s%m& $nher$tan'e& en'a"s%#at$on?
Ans: Polymorhisum: is a feature of OOPl that at run time depending upon the type
of object the appropriate method is called.
nheritance: is a feature of OOPL that represents the !is a! relationship between
different objects"classes#. $ay in real life a manager is a employee. $o in OOPL
manger class is inherited from the employee class.
%ncapsulation: is a feature of OOPL that is used to hide the information.
Q(: What do !o% mean ! stat$' methods?
Ans: &y using the static method there is no need creating an object of that class to
use that method. 'e can directly call that method on that class. (or e)ample, say
class A has static function f"#, then we can call f"# function as A.f"#. There is no
need of creating an object of class A.
Q): What do !o% mean ! v$rt%a# methods?
Ans: *irtual methods are used to use the polymorphism feature in +,,. $ay class A
is inherited from class &. f we declare say function f"# as *irtual in class & and
o*erride the same function in class A then at runtime appropriate method of the
class will be called depending upon the type of the object.
Q*: +$ven t,o ta#es St%dent-S./& 0ame& Co%rse1 and Leve#-S./& #eve#1 ,r$te
the SQL statement to get the name and S./ of the st%dent ,ho are ta2$ng
'o%rse 3 ( and at freshman #eve#4
Ans: $%L%+T $tudent. name, $tudent. $-
(.O/ $tudent, Le*el
'0%.% $tudent. $- 1 Le*el. $-
A2- Le*el. Le*el 1 !freshman!
A2- $tudent. +ourse 1 34
Q5: What are the d$sadvantages of %s$ng threads?
Ans: -eadLock.
Q1: Wr$te the Java 'ode to de'#are an! 'onstant -sa! grav$tat$ona# 'onstant1
and to get $ts va#%e
Ans: +lass A&+
static final float 6.A7TATO2AL8+O2$TA2T 1 9.:4
public *oid get+onstant"#
system.out.println"!6ra*itational8+onstant: ! , 6.A7TATO2AL8+O2$TA2T#4
Q2: What do !o% mean ! m%#t$"#e $nher$tan'e $n C66 ?
Ans: /ultiple inheritance is a feature in +,, by which one class can be of different
types. $ay class teachingAssistant is inherited from two classes say teacher and
Q(: Can !o% ,r$te Java 'ode for de'#arat$on of m%#t$"#e $nher$tan'e $n Java ?
Ans: +lass + e)tends A implements &
<. 'hat are the Object and +lass classes used for=
The Object class is the highest>le*el class in the ?a*a class hierarchy. The
+lass class is used to represent the classes and interfaces that are loaded
by a ?a*a program.
@. 'hat is $erialiAation and deserialiAation=
$erialiAation is the process of writing the state of an object to a byte
-eserialiAation is the process of restoring these objects.
<. 'hat interface must an object implement before it can be written to a
stream as an object=
An object must implement the $erialiAable or %)ternaliAable interface
before it can be written to a stream as an object.
@. 'hat is the .esource&undle class=
The .esource&undle class is used to store locale>specific resources that
can be loaded by a program to tailor the programBs appearance to the
particular locale in which it is being run.
<. 'hat class allows you to read objects directly from a stream=
The Objectnput$tream class supports the reading of objects from input
@. 0ow are this"# and super"# used with constructors=
this"# is used to in*oke a constructor of the same class. super"# is used to
in*oke a superclass constructor.
3. 0ow is it possible for two $tring objects with identical *alues not to be eCual
under the 11 operator=
The 11 operator compares two objects to determine if they are the same
object in memory. t is possible for two $tring objects to ha*e the same
*alue, but located indifferent areas of memory.
<. 0ow does multithreading take place on a computer with a single +PD=
The operating systemBs task scheduler allocates e)ecution time to multiple
tasks. &y Cuickly switching between e)ecuting tasks, it creates the
impression that tasks e)ecute seCuentially.
@. 'hat restrictions are placed on method o*erloading=
Two methods may not ha*e the same name and argument list but different
return types.
3. 'hat restrictions are placed on method o*erriding=
O*erridden methods must ha*e the same name, argument list, and return
type. The o*erriding method may not limit the access of the method it
o*errides. The o*erriding method may not throw any e)ceptions that may
not be thrown by the o*erridden method.
<. 'hat happens when a thread cannot acCuire a lock on an object=
f a thread attempts to e)ecute a synchroniAed method or synchroniAed
statement and is unable to acCuire an objectBs lock, it enters the waiting
state until the lock becomes a*ailable.
@. 'hat is the difference between the .eaderE'riter class hierarchy and the
nput$treamEOutput$tream class hierarchy=
The .eaderE'riter class hierarchy is character>oriented, and the
nput$treamEOutput$tream class hierarchy is byte>oriented.
3. 'hat classes of e)ceptions may be caught by a catch clause=
A catch clause can catch any e)ception that may be assigned to the
Throwable type. This includes the %rror and %)ception types.
<. 'hat is the purpose of finaliAation=
The purpose of finaliAation is to gi*e an unreachable object the opportunity
to perform any cleanup processing before the object is garbage collected.
<. 'hat is synchroniAation and why is it important=
'ith respect to multithreading, synchroniAation is the capability to control
the access of multiple threads to shared resources. 'ithout
synchroniAation, it is possible for one thread to modify a shared object
while another thread is in the process of using or updating that objectBs
*alue. This often causes dirty data and leads to significant errors.
@. 'hat are synchroniAed methods and synchroniAed statements=
$ynchroniAed methods are methods that are used to control access to an
object. A thread only e)ecutes a synchroniAed method after it has
acCuired the lock for the methodBs object or class. $ynchroniAed
statements are similar to synchroniAed methods. A synchroniAed statement
can only be e)ecuted after a thread has acCuired the lock for the object
or class referenced in the synchroniAed statement.
<. 'hat is the serialiAation=
The serialiAation is a kind of mechanism that makes a class or a bean
persistence by ha*ing its properties or fields and state information sa*ed
and restored to and from storage.
@. 0ow to make a class or a bean serialiAable=
&y implementing either the ja*$erialiAable interface, or the
ja* interface. As long as one class in a classBs inheritance
hierarchy implements $erialiAable or %)ternaliAable, that class is
3. 0ow many methods in the $erialiAable interface=
There is no method in the $erialiAable interface. The $erialiAable
interface acts as a marker, telling the object serialiAation tools that your
class is serialiAable.
F. 0ow many methods in the %)ternaliAable interface=
There are two methods in the %)ternaliAable interface. Gou ha*e to
implement these two methods in order to make your class e)ternaliAable.
These two methods are read%)ternal"# and write%)ternal"#.
H. 'hat is the difference between $erialiAalble and %)ternaliAable interface=
'hen you use $erialiAable interface, your class is serialiAed automatically
by default. &ut you can o*erride writeObject"# and readObject"# two
methods to control more comple) object serailiAation process. 'hen you
use %)ternaliAable interface, you ha*e a complete control o*er your classBs
serialiAation process.
I. 'hat is a transient *ariable=
A transient *ariable is a *ariable that may not be serialiAed. f you donBt
want some field not to be serialiAed, you can mark that field transient or
Conne't$ng to a /ataase
J/7C Q%est$ons
<. 'hat is ?-&+=
?-&+ is a layer of abstraction that allows users to choose between
databases. t allows you to change to a different database engine and to
write to a single AP. ?-&+ allows you to write database applications in
?a*a without ha*ing to concern yourself with the underlying details of a
particular database.
@. 'hat are the two major components of ?-&+=
One implementation interface for database manufacturers, the other
implementation interface for application and applet writers.
3. 'hat is ?-&+ -ri*er interface=
The ?-&+ -ri*er interface pro*ides *endor>specific implementations of
the abstract classes pro*ided by the ?-&+ AP. %ach *endors dri*er must
pro*ide implementations of the
ja*a.sCl.+onnection,$tatement,Prepared$tatement, +allable$tatement,
.esult$et and -ri*er.
F. 'hat are the common tasks of ?-&+=
o +reate an instance of a ?-&+ dri*er or load ?-&+ dri*ers through
o .egister a dri*er
o $pecify a database
o Open a database connection
o $ubmit a Cuery
o .ecei*e results
H. 'hat packages are used by ?-&+=
There are : packages: ja*a.sCl.-ri*er, +onnection,$tatement,
Prepared$tatement, +allable$tatement, .esult$et, .esult$et/eta-ata,
I. 'hat are the flow statements of ?-&+=
A D.L string >>Jget+onnection>>J-ri*er/anager>>J-ri*er>>J+onnection>>
L. 'hat are the steps in*ol*ed in establishing a connection=
This in*ol*es two steps: "<# loading the dri*er and "@# making the
:. 0ow can you load the dri*ers=
Loading the dri*er or dri*ers you want to use is *ery simple and in*ol*es
just one line of code. f, for e)ample, you want to use the ?-&+>O-&+
&ridge dri*er, the following code will load it:
Gour dri*er documentation will gi*e you the class name to use. (or instance,
if the class name is jdbc.-ri*erMGN , you would load the dri*er with the
following line of code:
9. 'hat +lass.for2ame will do while loading dri*ers=
t is used to create an instance of a dri*er and register it with the
-ri*er/anager. 'hen you ha*e loaded a dri*er, it is a*ailable for making a
connection with a -&/$.
<O. 0ow can you make the connection=
n establishing a connection is to ha*e the appropriate dri*er connect to
the -&/$. The following line of code illustrates the general idea:
$tring url 1 !jdbc:odbc:(red!4
+onnection con 1 -ri*er/anager.get+onnection"url, !(ernanda!, !?:!#4
<<. 0ow can you create ?-&+ statements=
A $tatement object is what sends your $KL statement to the -&/$. Gou
simply create a $tatement object and then e)ecute it, supplying the
appropriate e)ecute method with the $KL statement you want to send. (or
a $%L%+T statement, the method to use is e)ecuteKuery. (or statements
that create or modify tables, the method to use is e)ecuteDpdate. %.g. t
takes an instance of an acti*e connection to create a $tatement object. n
the following e)ample, we use our +onnection object con to create the
$tatement object stmt :
$tatement stmt 1 con.create$tatement"#4
<@. 0ow can you retrie*e data from the .esult$et=
(irst ?-&+ returns results in a .esult$et object, so we need to declare an
instance of the class .esult$et to hold our results. The following code
demonstrates declaring the .esult$et object rs.
.esult$et rs 1 stmt.e)ecuteKuery"!$%L%+T +O(82A/%, P.+% (.O/
$tring s 1 rs.get$tring"!+O(82A/%!#4
The method get$tring is in*oked on the .esult$et object rs , so get$tring
will retrie*e "get# the *alue stored in the column +O(82A/% in the
current row of rs
<3. 'hat are the different types of $tatements=
<.$tatement "use create$tatement method# @. Prepared $tatement "Dse
prepare$tatement method# and 3. +allable $tatement "Dse prepare+all#
<F. 0ow can you use Prepared$tatement=
This special type of statement is deri*ed from the more general class,
$tatement. f you want to e)ecute a $tatement object many times, it will
normally reduce e)ecution time to use a Prepared$tatement object
instead. The ad*antage to this is that in most cases, this $KL statement
will be sent to the -&/$ right away, where it will be compiled. As a result,
the Prepared$tatement object contains not just an $KL statement, but an
$KL statement that has been precompiled. This means that when the
Prepared$tatement is e)ecuted, the -&/$ can just run the
Prepared$tatement Bs $KL statement without ha*ing to compile it first.
Prepared$tatement update$ales 1 con.prepare$tatement"!DP-AT%
+O((%%$ $%T $AL%$ 1 = '0%.% +O(82A/% LP% =!#4
<H. 0ow to call a $tored Procedure from ?-&+=
The first step is to create a +allable$tatement object. As with $tatement
an and Prepared$tatement objects, this is done with an open +onnection
object. A +allable$tatement object contains a call to a stored procedure4
+allable$tatement cs 1 con.prepare+all"!5call $0O'8$DPPL%.$;!#4
.esult$et rs 1 cs.e)ecuteKuery"#4
<I. 0ow to .etrie*e 'arnings=
$KL'arning objects are a subclass of $KL%)ception that deal with
database access warnings. 'arnings do not stop the e)ecution of an
application, as e)ceptions do4 they simply alert the user that something did
not happen as planned. A warning can be reported on a +onnection object, a
$tatement object "including Prepared$tatement and +allable$tatement
objects#, or a .esult$et object. %ach of these classes has a get'arnings
method, which you must in*oke in order to see the first warning reported
on the calling object
$KL'arning warning 1 stmt.get'arnings"#4
if "warning Q1 null# 5
while "warning Q1 null# 5
$ystem.out.println"!/essage: ! , warning.get/essage"##4
$ystem.out.println"!$KL$tate: ! , warning.get$KL$tate"##4
$ystem.out.print"!7endor error code: !#4
warning 1 warning.get2e)t'arning"#4
<L. 0ow to /ake Dpdates to Dpdatable .esult $ets=
Another new feature in the ?-&+ @.O AP is the ability to update rows in a
result set using methods in the ?a*a programming language rather than
ha*ing to send an $KL command. &ut before you can take ad*antage of this
capability, you need to create a .esult$et object that is updatable. n
order to do this, you supply the .esult$et constant +O2+D.8DP-ATA&L%
to the create$tatement method.
+onnection con 1
$tatement stmt 1
.esult$et uprs 1 "!$%L%+T +O(82A/%, P.+% (.O/ +O((%%$!#4
Str$ngs 8A0/L.0+
Constr%'t$ng a Str$ng
f you are constructing a string with se*eral appends, it may be more efficient to
construct it using a $tring&uffer and then con*ert it to an immutable $tring
$tring&uffer buf 1 new $tring&uffer"!nitial Te)t!#4

EE /odify
int inde) 1 <4
buf.insert"inde), !abc!#4

EE +on*ert to string
$tring s 1$tring"#4
6etting a $ubstring from a $tring
int start 1 <4
int end 1 F4
$tring substr 1 !a$tring!.substring"start, end#4 EE $tr

Sear'h$ng a Str$ng
$tring string 1 !a$tring!4

EE (irst occurrence.
int inde) 1 string.inde)Of"B$B#4 EE <

EE Last occurrence.
inde) 1 string.lastnde)Of"BiB#4 EE F

EE 2ot found.
inde) 1 string.lastnde)Of"BAB#4 EE ><

Re"#a'$ng Chara'ters $n a Str$ng
EE .eplace all occurrences of BaB with BoB
$tring new$tring 1 string.replace"BaB, BoB#4

Re"#a'$ng S%str$ngs $n a Str$ng
static $tring replace"$tring str,
$tring pattern, $tring replace# 5
int s 1 O4
int e 1 O4
$tring&uffer result 1 new $tring&uffer"#4

while ""e 1 str.inde)Of"pattern, s## J1 O# 5
result.append"str.substring"s, e##4
s 1 e,pattern.length"#4
Convert$ng a Str$ng to 9""er or Lo,er Case

// Convert to %""er 'ase
$tring upper 1 string.toDpper+ase"#4

EE +on*ert to lower case
$tring lower 1 string.toLower+ase"#4

Convert$ng a Str$ng to a 0%mer
int i 1 nteger.parsent"!<@3!#4
long l 1 Long.parseLong"!<@3!#4
float f 1 (loat.parse(loat"!<@3.F!#4
double d 1 -ouble.parse-ouble"!<@3.Fe<O!#4

7rea2$ng a Str$ng $nto Words
$tring a$tring 1 !word< word@ word3!4
$tringTokeniAer parser 1
new $tringTokeniAer"a$tring#4
while "parser.has/oreTokens"## 5
JSP /Serv#ets
<. 'hat is the ser*let=
$er*lets are modules that e)tend reCuestEresponse>oriented ser*ers, such
as ?a*a>enabled web ser*ers. (or e)ample, a ser*let may be responsible for
taking data in an 0T/L order>entry form and applying the business logic
used to update a companyBs order database.
@. 'hatBs the difference between ser*lets and applets=
$er*lets are to ser*ers4 applets are to browsers. Dnlike applets, howe*er,
ser*lets ha*e no graphical user interface.
3. 'hatBs the ad*antages using ser*lets than using +6=
$er*lets pro*ide a way to generate dynamic documents that is both easier
to write and faster to run. t is efficient, con*enient, powerful, portable,
secure and ine)pensi*e. $er*lets also address the problem of doing ser*er>
side programming with platform>specific APs: they are de*eloped with
?a*a $er*let AP, a standard ?a*a e)tension.
F. 'hat are the uses of $er*lets=
A ser*let can handle multiple reCuests concurrently, and can synchroniAe
reCuests. This allows ser*lets to support systems such as on>line
conferencing. $er*lets can forward reCuests to other ser*ers and ser*lets.
Thus ser*lets can be used to balance load among se*eral ser*ers that
mirror the same content, and to partition a single logical ser*ice o*er
se*eral ser*ers, according to task type or organiAational boundaries.
H. 'hatBs the $er*let nterface=
The central abstraction in the $er*let AP is the $er*let interface. All
ser*lets implement this interface, either directly or, more commonly, by
e)tending a class that implements it such as 0ttp$er*let.
$er*lets>>J6eneric $er*let>>J0ttp$er*let>>J/y$er*let.
The $er*let interface declares, but does not implement, methods that
manage the ser*let and its communications with clients. $er*let writers
pro*ide some or all of these methods when de*eloping a ser*let.
I. 'hen a ser*let accepts a call from a client, it recei*es two objects. 'hat
are they=
$er*elt.eCuest: which encapsulates the communication from the client to
the ser*er.
$er*let.esponse: which encapsulates the communication from the ser*let
back to the client.
$er*let.eCuest and $er*let.esponse are interfaces defined by the
ja*a).ser*let package.
L. 'hat information that the $er*let.eCuest interface allows the ser*let
access to=
nformation such as the names of the parameters passed in by the client,
the protocol "scheme# being used by the client, and the names of the
remote host that made the reCuest and the ser*er that recei*ed it. The
input stream, $er*letnput$tream.$er*lets use the input stream to get
data from clients that use application protocols such as the 0TTP PO$T
and PDT methods.
:. 'hat information that the $er*let.esponse interface gi*es the ser*let
methods for replying to the client=
t Allows the ser*let to set the content length and //% type of the
reply. Pro*ides an output stream, $er*letOutput$tream and a 'riter
through which the ser*let can send the reply data.
9. f you want a ser*let to take the same action for both 6%T and PO$T
reCuest, what should you do=
$imply ha*e do6et call doPost, or *ice *ersa.
<O. 'hat is the ser*let life cycle=
%ach ser*let has the same life cycle:
A ser*er loads and initialiAes the ser*let "init"##
The ser*let handles Aero or more client reCuests "ser*ice"##
The ser*er remo*es the ser*let "destroy"## "some ser*ers do this step only
when they shut down#
<<. 'hich code line must be set before any of the lines that use the
set+ontentType"# method must be set before transmitting the actual
<@. 0ow 0TTP $er*let handles client reCuests=
An 0TTP $er*let handles client reCuests through its ser*ice method. The
ser*ice method supports standard 0TTP client reCuests by dispatching
each reCuest to a method designed to handle that reCuest.
0ow do you pre*ent the +reation of a $ession in a ?$P Page and why=

&y default, a ?$P page will automatically create a session for the reCuest
if one does not e)ist. 0owe*er, sessions consume resources and if it is not
necessary to maintain a session, one should not be created. (or e)ample, a
marketing campaign may suggest the reader *isit a web page for more
information. f it is anticipated that a lot of traffic will hit that page, you
may want to optimiAe the load on the machine by not creating useless
The page directi*e is used to pre*ent a ?$P page from automatically
creating a session:
RST page session1!false!J
s it possible to share an 0ttp$ession between a ?$P and %?&= 'hat
happens when change a *alue in the 0ttp$ession from inside an %?&=
Gou can pass the 0ttp$ession as parameter to an %?& method, only if all
objects in session are serialiAable.This has to be consider as !passed>by>
*alue!, that means that itBs read>only in the %?&. f anything is altered
from inside the %?&, it wonBt be reflected back to the 0ttp$ession of the
$er*let +ontainer.The !pass>by>reference! can be used between %?&s
.emote nterfaces, as they are remote references. 'hile it $ possible to
pass an 0ttp$ession as a parameter to an %?& object, it is considered to
be !bad practice "<#! in terms of object oriented design. This is because
you are creating an unnecessary coupling between back>end objects "ejbs#
and front>end objects "0ttp$ession#. +reate a higher>le*el of abstraction
for your ejbBs api. .ather than passing the whole, fat, 0ttp$ession "which
carries with it a bunch of http semantics#, create a class that acts as a
*alue object "or structure# that holds all the data you need to pass back
and forth between front>endEback>end. +onsider the case where your ejb
needs to support a non>http>based client. This higher le*el of abstraction
will be fle)ible enough to support it. "<# +ore ?@%% design patterns "@OO<#
Q%est$on 0ow can implement a thread>safe ?$P page=
Gou can make your ?$Ps thread>safe by ha*ing them implement the
$ingleThread/odel interface. This is done by adding the directi*e RST
page isThread$afe1!false! S J within your ?$P page.
Q%est$on 0ow do include static files within a ?$P page=
$tatic resources should always be included using the ?$P include
directi*e. This way, the inclusion is performed just once during the
translation phase. The following e)ample shows the synta): -o note that
you should always supply a relati*e D.L for the file attribute. Although
you can also include static resources using the action, this is not ad*isable
as the inclusion is then performed for each and e*ery reCuest.
Q%est$on 'hat ?$P lifecycle methods can o*erride=
Ans,er Gou cannot o*erride the 8jsp$er*ice"# method within a ?$P page. Gou can
howe*er, o*erride the jspnit"# and jsp-estroy"# methods within a ?$P
page. jspnit"# can be useful for allocating resources like database
connections, network connections, and so forth for the ?$P page. t is
good programming practice to free any allocated resources within
The jspnit"# and jsp-estroy"# methods are each e)ecuted just once
during the lifecycle of a ?$P page and are typically declared as ?$P
public *oid jspnit"# 5
. . .
public *oid jsp-estroy"# 5
. . .
Q%est$on 0ow do include static files within a ?$P page=
$tatic resources should always be included using the ?$P include
directi*e. This way, the inclusion is performed just once during the
translation phase. The following e)ample shows the synta): -o note that
you should always supply a relati*e D.L for the file attribute. Although
you can also include static resources using the action, this is not ad*isable
as the inclusion is then performed for each and e*ery reCuest.
Q%est$on 0ow do mi) ?$P and $$ Uinclude=
f youBre just including raw 0T/L, use the Uinclude directi*e as usual
inside your .jsp file.
RQ>>Uinclude file1!!>>J
&ut itBs a little trickier if you want the ser*er to e*aluate any ?$P code
thatBs inside the included file. f your file contains jsp code you
will ha*e to use
RST *include1!! SJ
The RQ>>Uinclude file1!!>>J is used for including non>?$P files.
Q%est$on +an a ?$P page process 0T/L (O./ data=
Ans,er Ges. 0owe*er, unlike ser*lets, you are not reCuired to implement 0TTP>
protocol specific methods like do6et"# or doPost"# within your ?$P page.
Gou can obtain the data for the (O./ input elements *ia the reCuest
implicit object within a scriptlet or e)pression as:
$tring item 1 reCuest.getParameter"!item!#4
int how/any 1 new nteger"reCuest.getParameter"!units!##.int7alue"#4
RS1 reCuest.getParameter"!item!# SJ
Q%est$on 'hat ?$P lifecycle methods can o*erride=
Gou cannot o*erride the 8jsp$er*ice"# method within a ?$P page. Gou
can howe*er, o*erride the jspnit"# and jsp-estroy"# methods within a
?$P page. jspnit"# can be useful for allocating resources like database
connections, network connections, and so forth for the ?$P page. t is
good programming practice to free any allocated resources within
The jspnit"# and jsp-estroy"# methods are each e)ecuted just once
during the lifecycle of a ?$P page and are typically declared as ?$P
public *oid jspnit"# 5
. . .
public *oid jsp-estroy"# 5
. . .
Q%est$on 0ow do include static files within a ?$P page=
Ans,er $tatic resources should always be included using the ?$P include
directi*e. This way, the inclusion is performed just once during the
translation phase. The following e)ample shows the synta):
RST include file1!copyright.html! SJ
-o note that you should always supply a relati*e D.L for the file
attribute. Although you can also include static resources using the action,
this is not ad*isable as the inclusion is then performed for each and e*ery
Q%est$on 0ow do perform browser redirection from a ?$P page=
Gou can use the response implicit object to redirect the browser to a
different resource, as:
Gou can also physically alter the Location 0TTP header attribute, as
shown below:
$tring newLocn 1 !EnewpathEinde).html!4
Gou can also use the: Rjsp:forward page1!Enewpage.jsp! EJ Also note that
you can only use this before any output has been sent to the client.
bele*e this is the case with the response.send.edirect"# method as well.
f you want to pass any paramateres then you can pass using Rjsp:forward
page1!Eser*letElogin!J Rjsp:param name1!username! *alue1!jsmith! EJ
Q%est$on +an a ?$P page instantiate a serialiAed bean=
2o problemQ The use&ean action specifies the bean2ame attribute,
which can be used for indicating a serialiAed bean. (or e)ample:
Rjsp:use&ean id1!shop! type1!shopping.+-! bean2ame1!+-! EJ
Rjsp:getProperty name1!shop! property1!album! EJ
A couple of important points to note. Although you would ha*e to name
your serialiAed file !filename.ser!, you only indicate !filename! as the
*alue for the bean2ame attribute. Also, you will ha*e to place your
serialiAed file within the '%&>2(VjspVbeans directory for it to be
located by the ?$P engine.
+an you make use of a $er*letOutput$tream object from within a ?$P
2o. Gou are supposed to make use of only a ?$P'riter object "gi*en to
you in the form of the implicit object out# for replying to clients. A
?$P'riter can be *iewed as a buffered *ersion of the stream object
returned by response.get'riter"#, although from an implementational
perspecti*e, it is not. A page author can always disable the default
buffering for any page using a page directi*e as:
RST page buffer1!none! SJ
'hatBs a better approach for enabling thread>safe ser*lets and ?$Ps=
$ingleThread/odel nterface or $ynchroniAation=
Although the $ingleThread/odel techniCue is easy to use, and works
well for low *olume sites, it does not scale well. f you anticipate your
users to increase in the future, you may be better off implementing
e)plicit synchroniAation for your shared data. The key howe*er, is to
effecti*ely minimiAe the amount of code that is synchronAied so that you
take ma)imum ad*antage of multithreading.
Also, note that $ingleThread/odel is pretty resource intensi*e from the
ser*erBs perspecti*e. The most serious issue howe*er is when the number
of concurrent reCuests e)haust the ser*let instance pool. n that case, all
the unser*iced reCuests are Cueued until something becomes free > which
results in poor performance. $ince the usage is non>deterministic, it may
not help much e*en if you did add more memory and increased the siAe of
the instance pool.
+an stop ?$P e)ecution while in the midst of processing a reCuest=

Ans,er Ges. Preempti*e termination of reCuest processing on an error condition
is a good way to ma)imiAe the throughput of a high>*olume ?$P engine.
The trick "asuming ?a*a is your scripting language# is to use the return
statement when you want to terminate further processing. (or e)ample,
RS if "reCuest.getParameter"!foo!# Q1 null# 5
EE generate some html or update bean property
; else 5
EW output some error message or pro*ide redirection back to the input
form after creating a memento bean updated with the B*alidB form
elements that were input. this bean can now be used by the pre*ious form
to initialiAe the input elements that were *alid then, return from the body
of the 8jsp$er*ice"# method to terminate further processing WE
Q%est$on s there a way to reference the !this! *ariable within a ?$P page=
Ges, there is. Dnder ?$P <.O, the page implicit object is eCui*alent to
!this!, and returns a reference to the ser*let generated by the ?$P page.
0ow do instantiate a bean whose constructor accepts parameters
using the use&ean tag=
Ans,er +onsider the following bean: package bar4
public class (oo&ean 5
public (oo&ean"$omeObj arg# 5
EEgetters and setters here
The only way you can instantiate this bean within your ?$P page is to use
a scriptlet. (or e)ample, the following snippet creates the bean with
session scope:
Xl4S $omeObj ) 1 new $omeObj"...#4
bar.(oo&ean foobar 1 new (oo&ean")#4
SJ Gou can now access this bean within any other page that is part of the
same session as: Xl4S
bar.(oo&ean foobar 1 session.get7alue"!foobar!#4
To gi*e the bean !application scope!, you will ha*e to place it within the
$er*let+onte)t as:
To gi*e the bean !reCuest scope!, you will ha*e to place it within the
reCuest object as:
f you do not place the bean within the reCuest, session or application
scope, the bean can be accessed only within the current ?$P page "page
Once the bean is instantiated, it can be accessed in the usual way:
jsp:getProperty name1!foobar! property1!someProperty!E
jsp:setProperty name1!foobar! property1!someProperty!
Q%est$on +an in*oke a ?$P error page from a ser*let=
Ans,er Ges, you can in*oke the ?$P error page and pass the e)ception object to
it from within a ser*let. The trick is to create a reCuest dispatcher for
the ?$P error page, and pass the e)ception object as a
ja*a).ser*let.jsp.jsp%)ception reCuest attribute. 0owe*er, note that you
can do this from only within controller ser*lets. f your ser*let opens an
Output$tream or Print'riter, the ?$P engine will throw the following
translation error:
ja*a.lang.llegal$tate%)ception: +annot forward as Output$tream or
'riter has already been obtained
The following code snippet demonstrates the in*ocation of a ?$P error
page from within a controller ser*let:
protected *oid send%rror.edirect"0ttp$er*let.eCuest reCuest,
0ttp$er*let.esponse response, $tring errorPageD.L, Throwable e#
throws $er*let%)ception, O%)ception 5
reCuest.setAttribute "!ja*a).ser*let.jsp.jsp%)ception!, e#4
get.eCuest-ispatcher"errorPageD.L#.forward"reCuest, response#4
public *oid doPost"0ttp$er*let.eCuest reCuest, 0ttp$er*let.esponse
response# 5
try 5
EE do something
; catch "%)ception e)# 5
try 5
; catch "%)ception e# 5
Q%est$on +an just abort processing a ?$P=
Ges. &ecause your ?$P is just a ser*let method, you can just put
"wheree*er necessary# a R S return4 S J
Q%est$on 0ow does ?$P handle run>time e)ceptions=
Gou can use the errorPage attribute of the page directi*e to ha*e
uncaught run>time e)ceptions automatically forwarded to an error
processing page. (or e)ample:
RST page errorPage1!error.jsp! SJ
redirects the browser to the ?$P page error.jsp if an uncaught e)ception
is encountered during reCuest processing. 'ithin error.jsp, if you indicate
that it is an error>processing page, *ia the directi*e:
RST page is%rrorPage1!true! SJ
the Throwable object describing the e)ception may be accessed within the
error page *ia the e)ception implicit object.
2ote: Gou must always use a relati*e D.L as the *alue for the errorPage
0ow do pre*ent the output of my ?$P or $er*let pages from being
cached by the browser=
Gou will need to set the appropriate 0TTP header attributes to pre*ent
the dynamic content output by the ?$P page from being cached by the
browser. ?ust e)ecute the following scriptlet at the beginning of your
?$P pages to pre*ent them from being cached at the browser. Gou need
both the statements to take care of some of the older browser *ersions.
response.set0eader"!+ache>+ontrol!,!no>store!#4 EE0TTP <.<
response.set0eader"!Pragma!,!no>cache!#4 EE0TTP <.O
response.set-ate0eader "!%)pires!, O#4 EEpre*ents caching at the pro)y
Q%est$on 0ow do use comments within a ?$P page=
Gou can use !?$P>style! comments to selecti*ely block out code while
debugging or simply to comment your scriptlets. ?$P comments are not
*isible at the client. (or e)ample:
RS>> the scriptlet is now commented out
out.println"!0ello 'orld!#4
Gou can also use 0T/L>style comments anywhere within your ?$P page.
These comments are *isible at the client. (or e)ample:
RQ>> "c# @OOF ja*agala) >>J
Of course, you can also use comments supported by your ?$P scripting
language within your scriptlets. (or e)ample, assuming ?a*a is the
scripting language, you can ha*e:
EEsome comment
yet another comment
Q%est$on 0ow do use a scriptlet to initialiAe a newly instantiated bean=
A jsp:use&ean action may optionally ha*e a body. f the body is
specified, its contents will be automatically in*oked when the specified
bean is instantiated. Typically, the body will contain scriptlets or
jsp:setProperty tags to initialiAe the newly instantiated bean, although
you are not restricted to using those alone.
The following e)ample shows the !today! property of the (oo bean
initialiAed to the current date when it is instantiated. 2ote that here, we
make use of a ?$P e)pression within the jsp:setProperty action.
Rjsp:use&ean id1!foo! class1!com.&ar.(oo! J
Rjsp:setProperty name1!foo! property1!today! *alue1!R
S1ja*a.te)t.-ate(ormat.get-atenstance"#.format"new ja*a.util.-ate"##
RS>> scriptlets calling bean setter methods go here >>SJ
REjsp:use&ean J
0ow can enable session tracking for ?$P pages if the browser has
disabled cookies=
Ans,er 'e know that session tracking uses cookies by default to associate a
session identifier with a uniCue user. f the browser does not support
cookies, or if cookies are disabled, you can still enable session tracking
using D.L rewriting.
D.L rewriting essentially includes the session - within the link itself as
a nameE*alue pair. 0owe*er, for this to be effecti*e, you need to append
the session - for each and e*ery link that is part of your ser*let
Adding the session - to a link is greatly simplified by means of of a
couple of methods: response.encodeD.L"# associates a session - with a
gi*en D.L, and if you are using redirection, response.encode.edirectD.L"#
can be used by gi*ing the redirected D.L as input.
&oth encodeD.L"# and encode.edirectedD.L"# first determine whether
cookies are supported by the browser4 if so, the input D.L is returned
unchanged since the session - will be persisted as a cookie.
+onsider the following e)ample, in which two ?$P files, say hello<.jsp and
hello@.jsp, interact with each other. &asically, we create a new session
within hello<.jsp and place an object within this session. The user can then
tra*erse to hello@.jsp by clicking on the link present within the
page.'ithin hello@.jsp, we simply e)tract the object that was earlier
placed in the session and display its contents. 2otice that we in*oke the
encodeD.L"# within hello<.jsp on the link used to in*oke hello@.jsp4 if
cookies are disabled, the session - is automatically appended to the
D.L, allowing hello@.jsp to still retrie*e the session object.
Try this e)ample first with cookies enabled. Then disable cookie support,
restart the brower, and try again. %ach time you should see the
maintenance of the session across pages.
-o note that to get this e)ample to work with cookies disabled at the
browser, your ?$P engine has to support D.L rewriting.
RST page session1!true! SJ
nteger num 1 new nteger"<OO#4
$tring url 1response.encodeD.L"!hello@.jsp!#4
Ra href1BRS1urlSJBJhello@.jspREaJ
RST page session1!true! SJ
nteger i1 "nteger #session.get7alue"!num!#4
out.println"!2um *alue in session is !,i.int7alue"##4
Q%est$on 0ow can declare methods within my ?$P page=
Gou can declare methods for use within your ?$P page as declarations.
The methods can then be in*oked within any other methods you declare,
or within ?$P scriptlets and e)pressions.
-o note that you do not ha*e direct access to any of the ?$P implicit
objects like reCuest, response, session and so forth from within ?$P
methods. 0owe*er, you should be able to pass any of the implicit ?$P
*ariables as parameters to the methods you declare. (or e)ample:
public $tring where(rom"0ttp$er*let.eCuest reC# 5
0ttp$ession ses 1 reC.get$ession"#4
return reC.get.emote0ost"#4
out.print"!0i there, see that you are coming in from !#4
RS1 where(rom"reCuest# SJ
Another %)ample
RSTpage contentType1!te)tEhtml!SJ
public *oid test"?sp'riter writer# throws O%)ception5
RSTinclude file1!file<.jsp!SJ
RStest"out#4S J
s there a way can set the inacti*ity lease period on a per>session
Typically, a default inacti*ity lease period for all sessions is set within
your ?$P engine admin screen or associated properties file. 0owe*er, if
your ?$P engine supports the $er*let @.< AP, you can manage the
inacti*ity lease period on a per>session basis. This is done by in*oking the
0ttp$ession.set/a)nacti*enter*al"# method, right after the session
has been created. (or e)ample:
would reset the inacti*ity period for this session to H minutes. The
inacti*ity inter*al is set in seconds.
Q%est$on 0ow can set a cookie and delete a cookie from within a ?$P page=
A cookie, mycookie, can be deleted using the following scriptlet:
EEcreating a cookie
+ookie mycookie 1 new +ookie"!a2ame!,!a7alue!#4
EEdelete a cookie
+ookie kill/y+ookie 1 new +ookie"!mycookie!, null#4
Q%est$on 0ow does a ser*let communicate with a ?$P page=
Ans,er The following code snippet shows how a ser*let instantiates a bean and
initialiAes it with (O./ data posted by a browser. The bean is then
placed into the reCuest, and the call is then forwarded to the ?$P page,
&ean<.jsp, by means of a reCuest dispatcher for downstream processing.
public *oid doPost "0ttp$er*let.eCuest reCuest, 0ttp$er*let.esponse
response# 5
try 5
go*i.(orm&ean f 1 new go*i.(orm&ean"#4
$tring id 1 reCuest.getParameter"!id!#4
EEuse the id to compute
EEadditional bean properties like info
EEmaybe perform a db Cuery, etc.
EE . . .
"!EjspE&ean<.jsp!#.forward"reCuest, response#4
; catch "%)ception e)# 5
. . .
The ?$P page &ean<.jsp can then process f&ean, after first e)tracting it
from the default reCuest scope *ia the use&ean action.
jsp:use&ean id1!f&ean! class1!go*i.(orm&ean! scope1!reCuest!E
jsp:getProperty name1!f&ean! property1!name! E jsp:getProperty
name1!f&ean! property1!addr! E jsp:getProperty name1!f&ean!
property1!age! E jsp:getProperty name1!f&ean!
property1!personaliAationnfo! E
0ow do ha*e the ?$P>generated ser*let subclass my own custom
ser*let class, instead of the default=
Ans,er One should be *ery careful when ha*ing ?$P pages e)tend custom
ser*let classes as opposed to the default one generated by the ?$P
engine. n doing so, you may lose out on any ad*anced optimiAation that
may be pro*ided by the ?$P engine. n any case, your new superclass has
to fulfill the contract with the ?$P engine by:
mplementing the 0ttp?spPage interface, if the protocol used is 0TTP,
or implementing ?spPage otherwise %nsuring that all the methods in the
$er*let interface are declared final Additionally, your ser*let superclass
also needs to do the following:
The ser*ice"# method has to in*oke the 8jsp$er*ice"# method
The init"# method has to in*oke the jspnit"# method
The destroy"# method has to in*oke jsp-estroy"#
f any of the abo*e conditions are not satisfied, the ?$P engine may
throw a translation error.
Once the superclass has been de*eloped, you can ha*e your ?$P e)tend it
as follows:
RST page e)tends1!package2ame.$er*let2ame! SR
'hat is the difference between $er*let+onte)t and $er*let+onfig=

&oth are interfaces.
The ser*let engine implements the $er*let+onfig interface in order to
pass configuration information to a ser*let. The ser*er passes an object
that implements the $er*let+onfig interface to the ser*letBs init"#
The $er*let+onte)t interface pro*ides information to ser*lets regarding
the en*ironment in which they are running. t also pro*ides standard way
for ser*lets to write e*ents to a log file.
'hat are the differences between 6%T and PO$T ser*ice methods=

A 6%T reCuest is a reCuest to get a resource from the ser*er. +hoosing
6%T as the !method! will append all of the data to the D.L and it will
show up in the D.L bar of your browser. The amount of information you
can send back using a 6%T is restricted as D.Ls can only be <O@F
characters. A PO$T reCuest is a reCuest to post "to send# form data to a
resource on the ser*er. A PO$T on the other hand will "typically# send the
information through a socket back to the webser*er and it wonBt show up
in the D.L bar. Gou can send much more information to the ser*er this
way > and itBs not restricted to te)tual data either. t is possible to send
files and e*en binary data such as serialiAed ?a*a objectsQ
'hat is the difference between 6eneric$er*let and 0ttp$er*let=

Ans,er 6eneric$er*let is for ser*lets that might not use 0TTP, like for
instance (TP ser*ice.As of only 0ttp is implemented completely in
The 6eneric$er*let has a ser*ice"# method that gets called when a client
reCuest is made. This means that it gets called by both incoming reCuests
and the 0TTP reCuests are gi*en to the ser*let as they are