0% found this document useful (0 votes)
44 views24 pages

Java Servlet Programming Guide

The document discusses the Java servlet API. It describes the servlet lifecycle including initialization, service, and destruction methods. It also discusses how servlets handle HTTP requests and responses.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
44 views24 pages

Java Servlet Programming Guide

The document discusses the Java servlet API. It describes the servlet lifecycle including initialization, service, and destruction methods. It also discusses how servlets handle HTTP requests and responses.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

-fboead.

ocesect veuest client each t


servlet tolable aniara libmie
ei elas
wrttes coz
in indepertant, platfrm *
Seriet Adientoaes
ef
platforn nat i .I+(cGa)intefaca
cialeendert.
ate
omoh a
ViSereY web tbtui
tfe Comuriati eet TE
t cient eac handle Tsoresr
ta
erly Ib
sSeYreY
ernter. erlet
client
SeYre? reg hetp
stae sener
ic the
ntantates
hen senrer cveb
that cast
yeay repone ava gereigaeYrlett
. i technolo an hon
aailable
f ies any §one servlet
ir ava
sigle acret uest ne atlanter shich
tane Theei uest. rahetoeen
y merny
sevlet proer. Serevate a ih Tun ot dee servlet
gerarat A
A yanicaly
tITNe SeeTi
tity extends
he that side erve
Serrlet
Tie ifeete Servlet

Three methals cerntral to the fe ycle gf servet

Q.Seyriac)

destag
Container
Ae serrlel
*javn servlet,ceaa an intane

The Continay calla tte înstare's inite mettod


the coaler ha a Tegeest foo te servlet,it calle
the intonce retho.
the in Stance, he contarror cals ffe

det
Te instance destryed ant rar bocd fr gorkae coecfien.

P
Thread ahitC
C Tôread
S SeriQC)

R tdastry
Servlet
contareg

web bo ser.Tb e b o s e s tho


()enter ORL to a

gerates http teert for thic


the eenver.The sereY
recehed

-this
httpte serv let. he Seret

netriered an lod înto the a r e

f the SereT.

(3) The seer ino kec the int (> mett et fho servlet.
(oales
This method is innolca) only cohen he serrlet is f i t
oramete con he nred to tha
ttalitron forameter
into tremey. Trittaliton
errlet that
that it ay
mny confare ita t.
vod innt (ServletConpig otig-tnott SevvletExcepion.
( h e serres inobe -he seTVt sserriec) re-fho Cuhichis
Ter, to
cale to moers the tTT reg. Ther erile the http
the client .
putie void service (Serlet Request regs SerrletRespane ver)
tbyowe ServletExeptBon ,toEx ceptton
acceph too objeet f SertetRequest, ServletRaspare
peorees o client reg and oespane to te elient. The
serrie C) met îs calte fos eonb
htp regett
S) inaly, tte sever deude to unoad the serlet from i
merne .the serney calle the dertreye methoc to destag
Serrle an release reouees

publie vid estro


T is called
the tife ycle s oo serlet.
mportant data carel
aRcate) for the sevlet and ts cah hon be
oiects
coleceA.
Serrlet
Acimple
s Crete ano compile senrlet Source cocle.

ile to ppopiat directy


Start seyYer,
the servlet.
start a
HetloServlet

import java.io, )
ipaot favax. serlet *) exterd! Geneie Servlet
publie elar HelloServlet
vad evrice (servlet Request req, senletResparse re
putalie Hnows ServletExartion, ToExcetion
SetontentType " tezt (htme');
Print Writer p Tesfeqetnriter)
p pintln ("<e> hallo "))
pwcloe();3
Open t e boose

http: / locat host:gogo/senet / Hetl Servtet.

belto

Arothey bogm
tmport Jav. Sewlet. *j
Impert jan.
csevlet bttpt)
impert ava.io.*)
fual'e ehes Somdeseylet exterds Http ervlet
pablic voi) doet
doGet (Aetp SetetReguett retep SerdetReronse res)
toowr SernetExcettoh, TOExceton,
at ContertType (" bextfbtne");
res . set

PintWites out =res.


resi getWritert);
pittnl <htmp);
ut. printnC hody')
Set irtin ("<p> "+'hele worle"t <r">+<Ibody)
bat ritin ("<ntn
ouf. close (,

* seYvlet ic a cìmple era cla.


* javan. servlet, jaax.serrtet. http are

SSeriekeuest HtplevlietRequet
Serslet Reparse Hkp eletRespone
ertens extend
class
fenerje evlel Hetp Servlet.

dofet> ’ qett repuestz an throws two exeptoni.


do4et" metha pexfoms he
setContentype text (bta))
Obfain PintNitey cbject foom Hetp erve HRespone by
cating getboiterl) matto.
The qetiter methe mu hot be calec afkey

-fhe ent type


content output a velid btnl doement to
typo. 1l tte

frortiter object elose pint wmter object.


Servtet progen doenot Ave Aain meth
beca tuse he sevvey poone -fhe n. loGetr, do Pott (> rets
as for the semlet.
The sevvlet ArE (Aseignment)
yova. sevvlet pac rage, savlet intexpaee, clace >jaraz.
rlet http focage, interpaca, clact.
serviet.
Serrlet Prreext
Roatig The Serletkeguet cla se inaludes
mettod fat alow
paronetes that
yoa o ad the anes end ra lues sf
ibdu de in client quest. o obtain the qey sti
parametar data the fbto iFg semetRequest ethe an
be csed.

enurneatton f
)Enumeratin getHeadneleyNanese) ’ Retuns
ralue repereiT Davametes hares.
S)ring get fareter(string hare)’etushs
pararneter vatue for
).ogl getfeyameter Values (Sting rame)-’setusnt aay
striy re sertig all values s

Postpacn. ttn?
<htnl>

<body "forrm? methar test"


<form "htp:/oralhat:o8o /servlet)Fbstperamseet '
Gettoh
<tabies
</td
hamole" Value
Ktd>iut type "tezt
'teet
</t
ta> hone <Itds
THdrinput type." tezt " name p" value
<ItY> <reable>

<inptt tpea'submit" vatue: "subnit"


<rbady <tht)
Postporaseret.java
int javk-servleb*;
astpaamevet extend Generic evet
puabie Cac

publie void serice (Sanettequet reg,SevvietRespene 7es)


ttrows SerretExeeotron,ToExeptan

frontNitey puw recpgetNritev;


Enumeratbn e- ve get P'aranterNaect);
tesbile (e.harMaretlerentt t?

Sting pae=(tirg)ehextElement ;
popint (prarre +

po ntln (patua;

Senet

phone: 231 P=
=|23

Subrai
Ånotter Eample
<HTML>
<head>
<TITLE>INVOKING SERVLET FROM HTML</TITLE>
</head>
<BODY>
<CENTER>
<FORM name = "PostParam" method = "Get
action="http://localhost:15311/Sample/SampleServlet">
<TABLE>
<tr>

<td><8>First Number</B> </td>


<td><input type= "text" name="t1" size="25"
value=""></td>
</tr>
<tr
<td><B>Second Number </B> </td>
<td><input type = "text'" name="t2" size="25"
value=""></td>
</tr>
</TABLE>
<INPUT type ="submit" value="Submit">
</FORM>
</CENTER>
</body>
</html>

import java.io.:
import javax,servlet.*;
import javax.servlet.http.*;
public class SampleServlet extends HttpServlet

public void doGet(HttpServletRequest request, HttpSeruletResponseresponse)


throws ServletException,l0Exception

PrintWriter out=response.getWriter();
response.setContentType ("text/html");
try

int x=Integer.parselnt(request.getParameter("t1 ")


int y=Integer.parselnt(request.getParameter("t2").
out.printIn("The sum is " + (x+y)):

catch(Exception e)

out.close():}}
Hrtr Reuets can Re ponces
Hanaing The Htp evlef che orida sociai2e) methls ttot
handle e ariovs type bttp reuects. fet cnl Port metkorls

#rp GET Requectt


Herig The be ident fier a seniet to prorer the HTr GET
euert.
Qbthn

form'
actioh= "http: loatbast :go/servlet (alovget ">
Kselect name color

Topton raue >" Red'> Reo optton>


<optton ralue^blue blue<lopter
7select>
<input fype='submit " vave "submit>

<ibay
<thtmR>
Tbe doGetes methoc) is oreridalen fo poores y htp Get
he getfermetevc=
metho Gf Heto ervletkeguest to btain the seleeton, haale
Ue eharacter
Aergth
Caterqot java
inport joavaz. servlet- )
"servlet.http.*j
public clae Catorget extends #etp evlet

publie voi doset (HEtpSerleRequest req> ep Servletkes,


tfroue ervletEreption ToException
colos : eq getParamete ("colosh),
stig
Ter et (artent Tepe('text/trd"?)
PönNites puwe gotWites ())
ps intIn ( co tor);

are
inctuale ar
farameter for an ATTP GET reues
par fhe URL that s sent to be web server.

http: locathost Pogo /servlat| fotongetcaer aRec.


URL and
end f
Stort sf eyn

Hartling Serlet that hanles Post reuert. The


is submitte
Servlet s inroce whe fov
The motod fparametor for the fom tag platty pepte at
Hhe PosT metAoo shoull be s
a .

Tforo hae = form method"


atton =hbttp: ocaltot :o/servlet/Celorpes"

Tha coostc methoc s overoldden to pees


getfarametey() motho
hèe
HtpServletReuest to otin he sefection that maate se.

publie noid doPast QtpseretRequest eg


HetpseriletResponse er) throwi Srvlettxception, TaExaptian
The pararreters fr tha http at e ae hot inaalad
pat he eL thot is sent tothe web seveo.
kttrs /oalhost:oso/sertet/ Calorpat.
The farameter hnes an Valye are sent in the body
the http requert. No rest etion is URL.Jergb.
Session
Sess ions ith
sereY e a b i estatsli shira. and naintaining
is etamin)
muttple client .Hetp ren
A specl icert ffe kno the re
Con s i l e e
bave
new cser else -he. nea be ooesse by atreoy altated
seSontD,

Collefon al aeolale it a
cgle
sesiontD sosein,

gerrer cient2

http e http vep


bttp res
SersjonLD AL

sesionTD =4235
bttp e
Sessron Tagaking
Suypovt fhe secsjon oncapt bf
javaan sernlet AeT
tfrPerion objet sore the sensanTD,
KOcatrg

sertet atle he get sesont) rntho on its Hets SevletRequest.


has Sescioni -thn getSecione) ceitl
etn the preiuy creatia) ctect.
* isNe (> Por HEtpsesjon object etuns a baolean
value
not.
epresera object is ereato

inpart java.fo k)
ioport ave. s e r v e )
import jave Servlet. http.*)
publie elass Helloser extends HttpSeret
int visits =oj
pablie voidl doGat (HtttpServlet fauet rep
HE Servtet Respone e r h o SevetEteptn, ToEx«ptton
cef ontertTpe ("textfttrna")
intWites out esgetWriter ())
Http Secion sections Teq getSe ssien(?;
f(secsion is Newc)

visits+;

pitin(visitt);
ut. closec)

3
ne ant the user har risited
TE the seceion is not
counter is ot in creamente,
the page before the
and Retrieing attibala
a hame-value pair
A se rston attibla s
simpy
tsbreb is storeol ih tetp eriop otjet.
s tEEpSesjon a e used to Store
uwo methas
and etiere
or over
) setPteibate (string hane, OEject obj) > create oject alue.
attibat haig tha gvern nare uwith the giren
lgetHttsbute(ing name) uhich returns the valle r
hll i there is ho
harre}
his hame in ta t t Seion ob]ec.
attibute cith
removeAibuteC) anc
wo more ethd
alio been
getAtiateNamest) Thenkga pape SeYer
Signin pa rorter rsigrin
any ho sesson
lpleae visitognin in paqe
welsmebaskpag

ewelone back
$et Rp
eg.from webTecbrdogbRefer
jaon,
seeroni
ehome backpage
seson Teimio afon
Secojan can be expired inalielatec.
a mefkoc atle
setNarInactireIntervat (int interal)- inteal epresenfs
humbe f secOls steseon is Valid
SeYVer Calls ìnra date) ashen the tirney omplet
seson TD is eceire
befare the heat reguert cortainin this Se sson as
Coetton imecretns the ne tha
get
-frrst cheateal ontanes
p e t t t AcoeMadTneeRetuns fhe tire he sen

sexton. SefNaxhacneDoterraeo

Session. iralidtel) lcille seso atteo 2omtb.


have hot
invalidatethe arra wi-thin t a t sesjm.
sancion,

cootier.

The siople st and


to ercange
hame
-the inosecconie is trogh cooies, coolaie is a
web Serres soncl to alient tachine
value pair tat a
httprapog, in the et- Cookie beade fetd. Boer
shorep this cootete ib client acte.

(elient set-cookie:jtesiontDr |23 Seyrer

sension E 23
etient serre

Cooleie ared to implement


automatically apter proressing getSeesion
Se son
tresbi
pmethod.
tfttpSecsion
lse

a coolee nane tsescloD


ereatirg
the cooi e, nd pat f the eane
settij
On subreqwnt Deguest, -he contairey geb
from te coolore
Qn sergion an aeocict en that se ecion ottb the
cument eguest.
gen hame, ralue (hey co o'e cla ns retthds)
hame, t g ratue)
Cookie(trng ’Refuns tame f cooleie.
Ss qetNamec> ’Rean ralele cooie.

sef errtil
bi setMa Age(nt seconals)
cooe expie.
Serrer sends
sefCooue: username sorehare /
hamevalue
elient sends exchye
ooe: erare SOnenarre an ho c(ent
Seré
coole

Coou'e cookie he Cooue("seshane, hame)


harnefatue pair
setting coolie .set NenAge ( 9*6o>}
cooete to etent
senig add eooeje to epoe beader
espanse. addooeielco e))
tHtandig teepreg and ttpoer ueirg coobies (hdd Coolete Sevylet java)
public hoidl doPast (
epene set Cartent Type (" textf btne")
hanes

Cooleie CDole he Cooe'eues nre hne}: / eeAte


boleie
Cookre. secMaz ge (30so;
espone. actCoobie (eooie); Nadd eoolie h hrer.
ervey "jsesronilet hrep= ca ltent c
hetpe. ev. of
erd
çessionlo
B4 |2 3 URL-f
fail. coolkie ifony woolesrewtia
onto nght
teRewst steke
ie once coolere the tats
in secsienit exchare tte
URe their, hot csoeis cesojohic.
XPet
Roor URL
enab eooleep
cooleietaragey-yRonge Toole’
cooee storeo
eoemoal) Ceooei cooleieJdicable emble
ererame); C"hello"+
swprintln stA 3
gethalue)
e licooUserNane
rnane")) efCcooletegetNanec)
.equols
[iI) cooleie cooleie Cookte
oepectqefCooki
es} coolcietc CookicCJ
Eext|btrns Cortonype
(" set sponie re
(· G,et vord
do public
jave vlet Coole)e
Ser Get
clasey
(nane; fordln
tegetWritert)) fuoepon W«iter frirt
UR
endeKedireetURL
C)
close put
"<itni)
<lbody
"+
meelick
enodeURL(
) +respone. <al
1 <hody
+
URL.this atertha
id
infosession
etSesiony seson sion et p
.getWibey
C); Tespanie PüntWmte
ot
C"text
|htm) setcontentType reeponee.
roEreepton tirour
tesane)
ServletRespanse Http
reest,Servletfequast (Http alaGet od publie
objec espanse ehosleURL
-
QRL, the enoa
response tatou
and fail ipoeie P lyonwores ewitinq URL
Itoductt to tsp
Jara serVy g eperale pgrmin ant pesentalion
SoUYce cole taine bin) cole , lise ctiver
and acttans. Tep continer tronelale tha isp eoce into jara erlet.
Jjava class convested to byte coale caliec clacf7le:
Sorce Gererlod |compi lef
eode Servtet Soer ce servlet Clacs
cole

Serrlef. The containes


be coel
A jr
tran la tes 7 t
the
servlet clacs.
java
java [. Toanclatop
2. ompilation
fistime it eten
dbaunent is vgeted
to the servet code cer hot fo tte coce.

Trenstate
webcorfeiner
Cciert oeg ompile
loaded -

to eaectte Cservlet clarc)


ethec
Three ke
*jpDety
jop Ses viec)
JsP elernents

Seriptlet
code
aeripttet.
java [statement ])
< Statement

<Y outprirttn ("helo"): >


Exprersion
< =exp

= co
cocnter
cunter get lount)%>
Dìretine
"Thoee tpee
pge
2, ine ley de.

page
< page lattibate value' . J >
< page iropott " java, io. "2>
, iheleiate
< ibctucle Pile'filenare " x

3. togib
toglibryuer" prap
tagtib 7-tabte
Comment
mmentjp --Xy
DelaTation
K!tatement [otatement J

Alo can metha leelaaton.


gie
-" pava " rtetype "tawt/html "x>
<Atnly <heediHe > emo <Atle> </heac
Khoaly bgoolor "aqua"y
<ALsometext <A
<r>r out: frrirtln C" jsp is equat tofo htrot java) I r >
date < = he eoae c). to.
Tolay
Jsp Exporeeton largge eu)
peial Ppare language desig rad for he
cation enrionment. Te puore f EL is T
ffer a cimple ny ta olerelbped
jva
sfanderd
in

+iepreeion
jep roarlcuP irectiver ilee Page ,disective
=" bethtne"/
:dieetie fag cortenty
directive inetuole fle-"ajsp">
TPEL has its

anal fnetiora)
courenarkup
jspmarkup
Special
pplieatie visonment. The igrad for e
Lwa to ioko
cimle ava
dvelaped Conhe con t% he top standad

irniet objecti(E) decnttn


pgeContezt Jsp impli iltiobjet
gethttilbtec
aesepe veguet.qetPttilbtet)
Seope
euest sesen, qethttibtac
sesiYnSeope arpicatton. qethtaatal
oppietonSope reuet getaeiec)
cookie
headeY
qauet. qotteade
pphcatten. getInit Faranetedt)
initsam
param meg uest getfa ametert
Iep oavlkup

diyetive lereht
t{html;
<jsp:lirective.pge conlbentType =" bex so
charet = -gSS9-"

<isp: dire etive.ineuale file"comnon adis clairesr


y ranlatin unit
Dntenattonalizion
fnations moceeiDartabase
g functions
X
X
Cone Core
Suiz Mane Namespa AreaFunetional
Areaf Funetbna JeTL
onespaee. wn o
funetora sepevate has JTL
ith each areas,
ettons Cne rtan JSTL
fage: isEror Page, emor btter, secion,
pog Otes
attbutes divecté
isia JeT
. curto
ownent, Jsp
wthinc cLre be to elene action. aditioral
hnechahicn bray tP The
litag
allows
attonf Cucton
dep-ormpliant proriola
an by be to
taires.
T<P tha by requir ae that
action starlayel
pefom
java atoh,
tronlate)
ito letFat
hat coole servlet
a (s
element aetion
Some
JSTL Core
Petions (Genesal oe oct
sel, emovee ,out,
out, urk, if, ahoote, fartach
Be: set vars vizits" sape:"applicatton
embeddod

<e:u vale sorawhae "


usebnana" value: kin Sag"/
¿c:paYam hoara:"
</e:url
URL rewitirg 9 ureane=kin tSam

(Lsek>set a ralue a vaviabe


versan tt
páanbup
value vañable hressy
seope vanable ressy to tte
the eting
rasable clean.
e:set var= ean >

sl e: set)
Synta var - VasNae
[sepe" ipagejreuatsionleppheaiong])
content
boy
<ie:set)
KC:renove) Rearavaiable
vartama
Cope"Ege/request/ansinpliotig'
content Body
tepe'tee ens'end gn" ="be begin
t "vorNama7
Var [var= forfach e:
forench> (e:
ahoose <le:
e) and bodyontent
e; fhan)
choore> SA<e:
ssteh Tava f
erert <eichoo.se)equiralent
<le:if
'oppieation sope= ='visits' <e:sef
Cortot bocly
gelelterion
atrng
Nare vas Lvar
bestondition faut <e:if Sete
akadari/ value='$ Ke:out
Value defautt
Pereml=
lfabe" "aue
vawe vnlue: Sspntar
a:porEach vars; begin:'a ende"g"
"

<ieifortach7
exampletsp vistt courste document]
inple
<html
qml"htp:lcoww a99ahrtrne
JSP|Page
zmni ajsp="http tjava.:suncom
e mlns:ehp: java. Sunornisp st|cere
content ype i baxt(htre />
<\sp:dineetie page
(ispoutfput
doctype-Toot-eleronte "Atne
Aactype- pablie sthetIEN

DTD|htrlttoct.dtd
<hoad
<tttte>

<Hite
<lhea d>

Vamabh
jop:cciptlat>ze,and updat thericit
/* initali
<ljep:sehtlet
<e:it
vicitg'>
testvaraicits seopeapplicattYn
{e:set valle""

e:if7
tmeS.
3 viewe) bean has page This <r7
<P
hellosd!
<p>
>+1ýeSvitits value
='arplicti o Stepe visits" vnrKe:set

You might also like