Servlet
Servlet
Browser
Server
Product Infy
ISBN
Conteot pe
Content type
Serve
EJB
Product
JSBN
info
DB
a Product
Requesio4 JofosMaion
Difference between CGI& Servlet -
CGI Ccorn moo Ghateway
Inte<tace
)lows process to read data
froro se parate
the HITP request b isite data to HIIP
esponse.
fig. oo iostantes of an application require a
program to process heis Loo req uest
simltenouslyJhe CGl proqram must be loaded
ioto memoTy
loo imes. Fach iosance beg'n
a
ne prrocess
Sserel communiate
can oh applets DB, or
via the Socket or RM mecbanism,
otherSofhoare
Life cycle of Sesvlet
Tbere ae 3 melhods of Servlet ife ycle
9)
destroy (
Ihey are inplemented by ever serulet d are
iovoked'at specific time the servex by
Assue that usex entess URL to a web a
( oethod of he
The server jOvoke the init
hy conf =geSerulekoof
()
SesslelCon
shconf. qeklnitfaameker (param4"),
sking
9) destroy l
oall4
Finally
the serves maydecide to unloadhe
Servlet rom is oemony. The server calls.
destroy ( method to
te reliaquish A0y resoure
hat aee allocated for the serulet The memoy
alocated for
be qarbage he Servjet & its objects CAD
collected.
it is wnloaded, by SeTver
dofost (O
web request,
client.
Server cherd dolrate ()
(O
HTtp Sesulet
fg- HHpSerelRequest
Out close (
d
import avax.servlet.
wHp.
ioport javax.serlet.
lm port java io thpSeDemo exlendsHHpSerdet
pubic class
xeq
publie void doet(HpSerletRaguest
ies)Aass Serlebaepton
HHpSejekespmse TDBupion
tes, sellandentype("eal(ktal");
Friohier out=es. gelhiter
out pin}o ("(hhrol) ody Kb) Hí<Ib
<|bady) <l htenl")
oudclose
3
In abDveeq. HpSesvlelRequest contaio
incoming ioformibn && Htinservle}Response obet
Used to send outgoind iofoxmaiooto cíent
In (Dmin4 data ioctude explicit & implicit
daa.
Explicit olata is supplied by user k
2 is Contained
contaios data
qtertyquery string that
from a form. Ioplicit" ata is HHp informaton
Such as request headex
data is enp1icit & implicit daoaTbis
Outqojnq
objec using
data isseot usinq fsintlile
& fosu) arded to the cJient
pointn () method
J5e fosmat of data sent to
clientis client
Sesvlet-name
Sesvlet -class
init-param.
<servefy
Kserlet-name) 1yervet <lserulet-name
Kserulet-class) myfackage.1ySerulelClass
lservet- class>
<Iservlet
<init-param>
<param-namey Pi <lea) -naMe7
20 Kparam- valyez
<param-va)uey 20
<Jin4
Patam)
<servlet -nappi9
KSe svlet -name y MyServet <Jservlet-pame
<url-patern > yseret |usl-patterny
<lservlet- mappng
<luoeb-app)
javax.
servlet pa
tkag e
Iotexfaces
)Servlet -
Declare life cucle mebeds for aservlet.
)SeruleHCoofiq -
Allousserylet to get ioitalizatioo paramekea.
4o
) Sevle+Request
Used to read data -from a clieot request
4)ServletRespose
Used to rite data to a client response
classes -
DGenexicsenvlet -
Implements Serveh & SemlelConfi
ioter faces
mehod
)destoy () servlet.
Caledat he Hme ef uploading
Sezuleoofa gelSewlek(onfg C
lootybject that contains
Reheni Seryle
ay inilialicaion paramete
)qSerletJofo () desc ribioq the Sevlek.
Rehuns 44
stoiog
r
serjce(SemvlelRequesh reg, Sertetkespnse
4)
geIoitfaramete(Ohinq param)
value o jojalizan
-
Rehns
()
qetSeruletName
Rehuzns name
ot the Lovoko seleb
ServletRequesl intesfae
Methods -
qetAHibudes(Shiog sle)
Returos Vedye of the atteibte.
Methods -
D Printiter qewiter
Jt rehnsPriorite
(
used to rite
character data to the respnse
2) public votd setCanteolength Ciotsize)--
Sets the conkest lesaih for the response.
to size.
3) public void setCooteotType (Stbia4 sk)
Sels the content pe for e respnnse
Joterfaces
DhHpSevlelRequest
Read data fros HTIP reques
)Cbokie
Allowsstate be stored on
a cient machine ioformation ho
)HtpServlet
ovjdes methods to bandle btp requet
respmse.
3) H}pSessiogFvent
Focapsulake session-changd euents
HHpServletRequest iotesface
Medbods -
sSting getrMelhed ()
Rehusns he G£T, posJ
HITP, method.
ShingRehros gGuerySháng(O=
query
Shinq qeRemoleVser (y
Retusns name of use makinq hitp
request ()
o int etRequesled Sessionld
Returns zessioo id oib bttp reques
)HpSession qetSessjon( bcolean
false rehurns valsd
Te
beoleá it
Creaea oe
else session
Curent sessios ()
6) ocolean isRequestedSessjonTalrd
Checks ohethex the http request
jth a session is
js vali
ociated sith
4sS0ciated
CuoieC3
qetCookies C)
Returns
arra4 of Cookies.
HpSeruletRespoose intexface
DVod
vold
addCookie C) -
Adds specified cookie to arespons e
2) seodfedirect (Shiog) -
Sends temporay redirectrasponse to
Cookie
Cookies are the echansm that senlel
uses to have clients bold a Sma) amouot
ofstale iofosmatioo associated uoittb the
Uses
A_Cookle is a soad) piece of iofosaion
S.6. stored Cpessistd) behieen the muliple
client requests.
A Dame, a
Cookie has a pamey
Such
a
as
ophonal
altibutcs
soest,path
Mazimm
a
&'doman qyaliers
nuober,
a
ge
Version
Fach xequest is conside redas aneo
reguest. In cookie tecbolque, we add (ookie
Uoith
Gknse trom
soxvlet So cookieh
Afex tbat Cache ofthe browSec-
if
cookie is reguest is the uses
Tbus We added sendD
ith request by defat.
Cogoite he user as eold usei.
T4pes of Cookie
here aeto tvoes o
on-persisteot Cookies Jo Sezvler.
Non-persisteot
TIs valld for siogle session ooly 1} is
remoV ed eachtme ben User closes the
brouSes
)Pessistent
J is va) -frd mutiple sessionI is
Dot removed each tiMe heo user loses
Hbe brouser. It Ss removed only if uses
Jogou
Advanye
Siople tecbnique
at
cf .
mintaining
client side
he
StatemairtaUned
J
Disadvanta
the
oi)
bowsex.
ot ork if coakieis disabl ed.
Constuctos
Constu ct a cookie
) Cookie (Shing name, Shin aJue
This Constucho Constyct a cookie
thh a specified ogme k valul.
pmethods
asa
,method
araumeothen
Session
It
objech
o
sessia
rehns
IH the
the cuthent
Cuurreot session
reates a neo
enist H1s method
method
doesn' etuns q ses SID cbject.
c
Bessipo
boolean geSessilon
ase () oelhod takes o
method unqum eot,then th's
rehusns the Cutrest sessioo aS a
sessloa
object If the cutrent
doesnt est sesslo
nul). theo this method retÔS a
An
HAtpSessibo object contains a data
mehods
2) EnymeratibO
Retusns
containing
the
()
pohsn he ime
langgeHCcahonlinse
getAtribute Names
names
enumesdHoo
of all
hen
C
of
bis
Skinq object
the attibte
sessiDo
. ua.
i mil)isec.
meosured
Created
ideniGes
Dinq getld()
Retusnsunigue
ideotifiex that
sion
loo4
Retuns he
getlManaciveIoleval
4he sesSioo ()
acCeSses, remajnsmaximuro
onen ime, io Sec.,ha
hetueen
client
longgetLastAcessedlirne
Retuns the C)
a
req4est in the last timMe the client sent
session, as he Dumbes of
)SesleContet
Retusns
qeSesvletCoolent
he
()-
ServletCorotent of the session:
8) Vo)d iovaidate C)
Ioratidates bis sessioo
4) booleqn isNes()
Retusns tne, if the unaware
client is
of he sessioS or if the clheot doeso4 jcio
4he sessioO
4he attoibte.
ot i)
atter wwbich he
I2y void ahiue io sec
sedlarInaciveloenal
Specigies
iovalidatcd.
irDport
import Javax-sexvlet
javax.
ioport java.io.
serulethtlp
k *
public
assSesDemo exleods
HHpSexvlet
publie void
doGie
(pSerolelRequest reg
H**pSesvletResponse res )hsous
Servletxepli
L I06xceptim
res: sekonteoype
erlktrnD:
Pootitex ores4eliter
HSessian hs - res qetSession()
oupinHn body> Sen
1d'+ks gekTd);
ouhpioho(me4SqetMloTnacioteral0
SsetManInacivolesvas (20 a 60D; 7
out piolg(hAfee me to 2omio,
changing, bne
outpiotosedMaln ach vdIokerval (O)
H tp request header
1dentHG es the Mime type
Accept
Accept-languaqe
conkot-1gh
4
Cooki e
4Host
Usex-Aqent
IModGed
Sioce
UomodiGed-Since
MiME type
audio basic,
ioageJpeg
tezt |Css ,
audiolmd)d
imagelpng
, innageit >
text|htnlL eat plain', text /xm
pplicaHon /pdf.
Stahus Codel
short messaqe Con stant
Contioy e SC-CDNTINuE
Accepicd SCACCEPTED
200 ok SCOK
204 No Contest SC N_ONTENT
found SC_FOUND
404
Unadhoxjzed
SCUNAUTH 1ED
OR
SLNOT-FOUND
Mehodohallsoed SCmETHOP_NOLALLO WED.
Iotesna
Serverertat SCTNTERNAL_SERVER
ERROR
SO3 Sesvice unavailable SC SERVICEUNAVAI
LABLE
RequestDispatcher in Servlet
The kkquestDispatchex inte sface prDuides
the facilihy of ispatthing the yequest to
anothe resource, it ay be
btol, sexvlet ox
oY
car aso be used
ioeóface can to
jsp.Tbs content of another resoUrce
iolucle he
bere aee teD0 methods.
ayso.
forwand k include C)
public vold
osu0ard (SexvletRequest
Sesvlekfesponse reg
res)hr.0s
SeavlelExcephD,
10€<ception
Foru ards
anothe a Rquest from a sesvlet to
resousce (servlet Jsp fle
o0he seTvex.
or Hto)Hl)
<ient
request
(Servlet ) foru0ard
Servet
Response ís
brouoses |Response generate
Respon se is sent
back to boDse |Responsel
CResponse of ficst servlet (sesulch 1) is nat displayed
to yser)
chent incude
request (serulet 1 servlet 2
response of Sevlet2
Anad response siocladed in servleti Respoose
is generakd
na
response is Response
back o Sent
client
eoter t)
Passoosd
enter hto1 Joginl
bhro)> kbody>
Kform actonhhp:/)
lacelbostis08D/b eaog)
method-aeti
Name iopu tMpe = "Hert"
name=nm'7
fassasd
<ioput
ye
inpu
tpe-passLond name po
type=submit' value="login',
<jfoso) <lbodyzkJhtgly
ogio java
ioport javaio*}
iopert (qvax.sesvlet A'
import avat:servlet. ttp.*;
pablic class Logio ertends HtpServ| et
LO6<ephin
ses.selCooteoEType ("Hent|htnol");
Priotites out res. getwikr()
Shing n= req qetfakbanetee ("nh):
Shih p=reg glRarameler (puo)
iEGéquall hccsce')
RequesDispatcheç rd - req.
qeRegdestDspatbex ysoel.
else
out-pin+nso Fstos'D
KequestDispaehes rd =req-
getRequestDspaher
3 rdindude enteshtesbbpacher
(req:res);
Sr0prtjavan.serviet-*.
Sing
outyint (1
3
seodRedirect () method
response
Jbis oethod used to redirech
Metjsp ar
Ao be se
anotber
ho]hle I} resousceooell
accepts relaive as ell as
absolude pe URL
be fora d () p sendRedixect (U
O
Difercote
sendRedirect )
) w0ks at Sesvex side. ) osks at cient
side.
an
sendsan
Sehds
e I sends he saMe
requeste respoose obs reguesl
to anothes senvlet: ojbio &
3> Sbe used
ca
y Conterntz Encod)nq
Conto} Tye
expires
Last-modified
95 Jocahon
javax Servlet
javanSetv)et ttp*
Sotestfaes pSeruletRequesh, HHpservlelRespar
HHSeasian, HHpSessien Cootex
Htp SessionLis4enes
lasses H9pSeaulel Cockie, HHpStvb}Reg
Wapper, HhpSenlelfesponse kae
Grenesc Sesyet H4pSeslet
5 Super Class ofHHpSesv let.Dsubclass ofGieresc Sere
o Protocol indlependent Rhand le ProtoCo)dependent Chand)e
aJl Hype of protscol htp, Dnly http protocol.
Smtpttp eh.
3) Ony suppart seruj'ce (
method Handle ony simpl4 dofet(), daDelele() dotead
reguest. doate(, doOphons 0.
4)favoaxSesvle}a pack javax.Seruleh: kttp. * packag
Request 2 0eb frocegs 2
Seve 3
ProCes
Sesvet
Request 2 Thread
Leques3 S Jboead
het Post
)Cached te muo is )
Never cached, doo
broser bisty remalo io broOser bistray.
20 No
Length restoi ctin length teshichm.
204s characters.
> Used ony retieve daba9 Vsed o suboit data.
4)J}is less secure )J ss ore SeCure because
becawse dato sen is
dat sent is not par of
direchry
Cut the SDemo.class tile froo D:/|DY8 4
folder & paste inho c'\programtles
Apache Sofhoate foubdatinYomcat 70\
webapps seema\ wEB-INF classes
folde
staxt the
ch pge