0% found this document useful (0 votes)
30 views

Servlet

Java and advanced Java concepts

Uploaded by

Pratik Nanavare
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)
30 views

Servlet

Java and advanced Java concepts

Uploaded by

Pratik Nanavare
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
You are on page 1/ 36

Sexvel & JSP

The usex intexface qatheos a tequest from


persor Oho uSe the J2EF Cppli aion
toxwards the reauest to aa component to
Processinq The component that processes a
xequest is built eitbeca java servlet
OY using
Sevlet is a
Smal) proqram that execte oN
on
the Server side of a we onnecion.The applet
extends the fun chionality of eb
browsea. Sexvlets
dynamicaerlels dynomical ly extend he
funchonality of web sesver
Cooside'r a request eb fage
fo a static wcb
through web browseY. A user entexS a
URL
CUoiform Resource Lo cator) into a browses S. Jhe
bxoses qen esate an http tequest o the
CPpTopmate Web serves. Tbe neb sesve
the equest to aspechc hle. That le is
yetusD ed io an bfp response to the boses.
The bttp heades in the response gets the tyf
OF the cootents. the Mtipurpase Inteonet
Mail Fxtension (MIME) are uss éd for tbjs purpose.
The HTML SDuste Code. of a h)eb page has a a
M1ME type of text or btml.
In case of dynamic content such as an
ooline stote uses a DB to store ioformation
ahout its business. The jnformation wod include
Hems for Sales, pri(es, availability orders etc
Ike Conent of suchdunamic paqes must breflect.
the latest ioformaion in the B,
neasl days ofa the web a sex ves Could
dynamically construct a page by Creaioq
Seperale Process to handle each clienF request.
The proCess DoJ open
open
connectioo s to one
the
DBs. jn order to obtainhecessaY
informaioo. I!
It Corpmuoiate oith the cb sesves
Via as intesface koon 4s CGI Comon Gae
Oay Ioterface).

Java Servlet e CGl proqram ming


J2EE applications LSes client,
ligbtdeibt
a brow ser, that contains Hle or no
typically
processinq logic. A middle layer poqram based
on the webserver bandles alprocessing'
pro CeSSing
SesVe-s)de progra hand led
Origioadly
cient requests by using
he Calobich was
Pesl other pnramming
programmed using
lanquages.
Java Servlels & Ca both provide the
Same basic funcionalihy i.e. crplici & implicit
data is sent from a cient to server Side proqram
io theform of a request i.t.
i.ea Processed aooth e
set of explicit & implicit data is rehurned.
Explicif datais inforMaion eccived from
eiher enteted by the
the cient typically
yses jnto the u User intesface or qeeraed b

the user intesface idself.


user)d, passDoTd are erplicit data that
i
can be generated by a bro
broser
0 Ser applet or ,
CustoM cheot.
roplici data is HT TP iofornmation 1.e.
gene rated by the client (i.e, browser) ratthes
than he
use HT1p ioformaion Contains daty
about the reauest.such as he coOpressioN
scheme Cookies R media ty pes. This ioformatios
used by the ja vo_sezvdet to leaxo abDt he
eques itself USer
explicit datasu Product infor

Browser
Server

Product Infy
ISBN
Conteot pe
Content type
Serve

ISBN froduct Iofor


1SBN
java k Conkent type
conteot hpes
SeTvlet
Irsplicit dak
Product
Sefor

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

2> A variehy of different lanquaqes 0ere used to


bwld (Gl pro qxam Such as
3) The (GI Sulered sesious pefomance problems.
JI was texms of proces sor & memoxy
expensive in
resoUsCes Create a separate process or each
cheot requestI js also erpensive to open & close
he DB Conne chon s for each cient request.

The Cál progam were no platfrm indepencent.

s) CaI program is no persl slent Onte a Cóu proqraa


tezminales. a] dat used by the p js losL
cess

&cant be used by the othex CaI proqrams,


Serrket

) The Servlets Are execwle wjthio the address


Space of the eb sever
2) Serle
perfonance js
than Cal
I} not tica ntty grealer
necessary to creale' a separate
process to handle each olient reaues First,ooly
0ecoPy
the JVM
of ajava sesvet is loaded ioto
DD mater the number ofs)mltaneous
tequests made to the java servlet. Fach requet
beqins a thread to he lava sesvlet Tather than
ane pr0cess, btch aaves memoTy uSAge on
the erVer e incea ses response ime because
one Copy of the (ava serulel needs to be
lo aded ioto
ota mêmory fach copy of the Sertet fs
a hread. There aill be muliple copies of the
Sesvlet.

3) A java servel has persistane, because jaa


seylet remains alive atkr the Tequest is
fwAled

)Servet are plalform indepeodent


plalform independeot, because they
are wiHen in java

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

bro ser Tbe browser then_ generae an HTTP


equesF fox tbís URL.T5ís reques is then sed
seot to the appropriale server Tbis HTtP request
is xeceived by the web servex. Tbe serves maps
Hhis tequest to a paxticular servle. Jbi's serulét
js dynamiay retieve k Joaded into the
address space' of the ser

( oethod of he
The server jOvoke the init

sevletThjs method is invoked ooyhen the

sere is frst 1oaded into memoy. IÍ )s passible


to the sevlet so
paramelers
to pass ioitaliraion
ifself.
confiqure
i} may
ubie vo)d ioit CO thros Serulelfxcephon

hy conf =geSerulekoof
()
SesslelCon
shconf. qeklnitfaameker (param4"),
sking

read the seTver-pecihicinitialja


abore method. Hon parameter.
Usiag
Ihis method
the
is Called ogw once .Io ioi}Om ethod
Sesvlet Cheate
that H oil) be using
e iothabizes 4he resoures
wobile baodio gtbe requests.
pubtie void il
public vojd ini (Servlel Gorofg con)thrnsSerwlebeption
T5fs
oethod tate SevlelCoosg objec
as a
parametey. Jf sezvlet caot iniHale the
reSUTCeS necessary to handle tequests,he
jot( meho ahoudhow5 a Serdelfxcepion,
2) Sevi'ce ()
he SeTves iovoke s heservte c) method
of the Senvle. T5is roethod is called to process
the btt req uest. I} js possible for the servlel
to read data that bas been proded in the
http reqyest. I! also osmwate an
http
tespons e for the client.
The seTvleE remains io the servers addres
e is availab|e do process any othe
tpace bttp
eguest receive d tom clieots. his method is
oa)led by eah http request..

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.

Serve loadhe Servlet


Server cretes
one r mose instane ofhe
Servlet class

Serve clls he ioit of each


C method
s esvlet instance

Servlet request is seceived

servleFselects sevlet instance & calls its


service C) oethod

servle}'s setvi'ce C) method processes tbe


request & ehusns
Tehurns olp to client

sevlet wait next request is received ox


un ti)

it is wnloaded, by SeTver

Sesver wnload the servlet afes caJiog

its desoy () method


sCvlet Jife cycle
Types of
Servlet
Tbere
Servlets
are
ar
tD
e too main classes or types of
Java Ses vle
Gteneric Servlet 2 H HpServlet
does oo
have oaio() method
uahich i hy a1 sevle}'s must ioplemcnt
Wby
he
Javax.Sere.Servle} iotesfale
Ihere GenexicSexvlet
requests.
class handles Hpe a)
The
HpSeswet class handles procesSes
Htp tequests.
JE you decide to exendthe GtenesicServle
class, you must implemet the servite O
metbod.he Genesic Servles serviCe C)meHhod
hasbeen oletined as an abshact method.

chent web Sesves 3


teqyest
GenexicSerde!
Servcec
The 2 tobjects that the seiceC) mehod
receives are k SevletResponse.
SerletRequest
Jhe SerdelRequest abjach holde the infunai
intrmahanon
)e. being sent to the servlel, obereas
the beinghe object is here you place
SethetResponse
he olats you want o
send back to thestYvex
The Hpsesvlet class has already
the follboing
implemened i} for you
1tp Sesdek.
publie vojd sevice HHp SesvletRequest req,
res osSeslelfxiepton,IbEetion.
)thnas SeaulelfE
Respmse
wben
HHpSevlet, serv'ce C) method is
jovoked j! reads the stored io
he
tbe reques
metbod ype
iovoke.
&
detemines obich metho to
10vOke.based on -his valuo.
method
hype is
valve, Jbere are he
methods hat you noil] Oant
ovesrideJE o
1f method type
type is
is posT, it oil caJ] dofost)
> doelee( )
dohet ()
Servie (y

dofost (O

web request,
client.
Server cherd dolrate ()
(O
HTtp Sesulet

fg- HHpSerelRequest

The HttpServletRequest k H#pSeruletResponse.


alasses are just erten sions of Sesuletfequest
E Sevetfesponse with tp specifc information
stored in thenm
URL in a wdb brlser
a
hen you
YOu tequeat
he GET method is used for the tequest. A Get
xequest does nat have a body (ie.body is
responseshowd Conaina
)The
emphy
Oith the tesponse data é header-feds i
desesibes hé bod
A
simple java
sevlet -
jopoxt javax.
joport java. iosevlet*,
public class Seel)emo eleds senesicSexvlet

publie veid seice (SedetRequest req


ServlatRsponse res)thoas Secvlel Exceptin,
TOEreplion

tes. setonleotlype CHent|htrol);


Printhitex outres qetwiler O.
).
outpioHa (" Khtml))

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

dependent HIML 0r XML paqe. if client is


forma of

used to sel the


seConkntype C) method is

the Conteot type HTp beades


Value. -for of
iofoxaation. Coont type. idenhfes the hype
being sent erplicih y.
documer i
DeployrMent Descripto
a tle tocaked in he WEB-INE direchosy
that COntrols the behavi ourr of a
TSP.
the X M
he fle
beades
is alled the .h java seou
4)e
elemeot
& ontains

DoCTYPE & web-aPP


eb-app elemeot shoud contalo a

servlet element i4h 2 sub elements.

Sesvlet-name
Sesvlet -class

init-param.

Servlet-ngme element contasns he ngme used to


a ccess the jav servlet.
Sesvlet-Class the
is class name of the ava seTulet.

ioit-param name of an iniialicatio o


is the
is made
parameler ie. used Obenever a request
to the java sevlet.
9ame oF java 3esvle t wHbin the eb.o
ameohe java
e.9.
Mserlet. Ihe class n

Sesvlet is yfa ckaqe.My ServletClass. he name


paametr is P1 wbose value is
of injHaizahon
20

<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

Sam for readioq request foma cient


sServlelDutputSheam
Sheam for nitin q respones to a cient.
5SexvlekEacapion
Jndicaes a Sesvlet erro occurel.
S) Uoavaí lobleExcepHon
Sexvle intexfale
JL has. 3 Metthods io)}(O, serve(k
cdesteoy(

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)

process a request trom a


JE js called to
requests &seods esponse
clieat. Jt reads
back

SexuleConfia ioterfacealows a SerVlet


Tbisotesface oben loaded.
date
to obato Coniquraion
Methads
DServlelContext
2)
rehsn
Sevhet
a
9eServleContert() serret
cootcat for the sesvlet

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.

be se,qet ox removed frofs) request,


SessiOO
application scope
iat gkConlentlangth (J
Returns siak of the equest -dis tehusn ed
Is unavulable.
) Stsinq qetfroto Col. () -
Rehyns descaiplion of the protocol
y Shinq qetServerhlane
ReteDS Dame ot
()
SeVe

Reuzns naqe Server

9Btbinq qetRegote Addy(


Retunn sicg eqwvalent do lient
JP addrus.
2Shinq qetRemotedost ()
Rehn shing equivalent to cient host
Dame
E) Sin4 qetSchemeO Scbeme £ UR)
Rehuns toansmiss)OD
Such as http, ftp eh
SesvletResponse iotexface -
This
Js used to reten respoose ba
to the client.

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

avax- servlet.http package

Joterfaces

DhHpSevlelRequest
Read data fros HTIP reques

ojtes data t HIJP respmse.


)HHpSessicn
A)ous sessio0 date to be read l utteo.
Classes

)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

aClient using speciied redirech locaion

Sends error response to a c)ieot.

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.

from set io Ceoie


Oy tezhal ntMation
Cookie class
his class
UASlOg broWides he of
CoOkies -funcionab
Cookies
Uses to have dre he mechanis that aservlet
ciert balA ema) amouoF
state\otormaton ot
he
Coai es
associated
are
oh use
sing HTJe assigned by server &
added. Web response headers be Rlds
felds qet
20 bopsers
Cookies Suppats
4kB pes host o at leash eacbot

Constuctos

Constu ct a cookie
) Cookie (Shing name, Shin aJue
This Constucho Constyct a cookie
thh a specified ogme k valul.

pmethods

D public void se!Mantge Ciot age)


aqe
Sets the maximum age
Seconds,
()
2) publbc Stioq qelName
Rehurohe4Me of the (ookje.
()
public SingqetValue
Retur vlue of te
9 public
selName(SingOame)
void Ame oECookie
the Dame
the
hanges
)
publlC sel Value
vold Sting vaue)
Sets the value tox cookje
qe!MaxAge C)
Retusna paxim«m age oE coOkie

publ)c vold selDoman


aa
(tobicha
(Sthio4
dogain
bm) cookie
Species
belonqs to.
Tracki4
A Session
Sessioo is
req uess Serice Created each time a lieot
fror a java
JavaServlet servlet.p
ptocesscs to tequest
R
atter obichthe responas.
sessioos
HTIP is a saleless
hat there iso proto Col,rcAnlng
meaning
a0y hold ovex from preious
Sess)ons. hereoe
Sesson het is nD to tack
usinq HIIP.
A uslelet
Java Gervlet s capable Df trackinq
Sess)ons by the HETp' HttpSessioo API.
using
The HAlp SessiooAt uses the 44tp Sessios abject
ie, assbcialed oith the HttpServlRequest o
deteomioe if the requesh is a cooin uatoo
fiom an exisiog session er is
A jav Serlet
Ser qelSession C)
calls the
melhod of the HHpSezuletRequzs abject,
wbich retusns a0 HpSessibn abjec iEit
a
ne sessi. Jhe qetSessionC)rethod
one rqumentOhìch js boolea)
heq ures () method doesp'!
IP the qetSession
3uent then this method rehoos
USe
Coxishog
the session o creates q
e ithex obla
refuns the session
neSessiDn &
bcoleao tye as an
hk takes a
TE

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

ASsociated uoith each


tsite cfthe key:A'key
key s an
sessiooYoucan read a
Nalue of an atibute by the Http Sesslah
calling,e
Obfecta qetAHibute C) nheth od mediey
mod ify by
clling selAtibute C) mehot.

mehods

Object qetAHaibute Shaing (


Reho objel, if rhet tound
oo)
theo retan

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

)void removeAteibute (Shing no)


h
Removes the objec assoclaked

4he attoibte.

) vo)d setAtibute (Shinq


wae s an objeto
om, Object
the
vad)
atteibuke

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.

HIIP- slatus Codes

Stahus Codel
short messaqe Con stant
Contioy e SC-CDNTINuE

Accepicd SCACCEPTED
200 ok SCOK
204 No Contest SC N_ONTENT
found SC_FOUND

307 Teoporary RedirectNo constant defoed

301 moved PesmanenH SCMOVED PERMANENTLY

Not oodjed SCNOTMODTFIED


304
400
Bofequest
SC BAD_REQVEST

404
Unadhoxjzed
SCUNAUTH 1ED
OR

SLNOT-FOUND
Mehodohallsoed SCmETHOP_NOLALLO WED.

Iotesna
Serverertat SCTNTERNAL_SERVER
ERROR
SO3 Sesvice unavailable SC SERVICEUNAVAI
LABLE

Sos HHp veYsion pot SCHT_vERS10N_NOT


Suppted SURPORTÉD

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)

2) public void joclude (SerdelRequest reg,SerulelRespmy


)
res tbros Serlekxephm, 106xephan

Includes the Conent of a resoure (servle

TSP fle ox Hio)Gle) io the response.

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

public void dofost (HHpSerlciRequesh reg


HtpSeauletfespnse restbous
recthros Sexulebxceeti

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-*.

pubic class oel ertends HHpSeslet

pblic void dazs dogek (HHpSezlelRequest xto.


HHpServleRespmse r)ihos Senvletbxcephon,
IOExaçHon

res seContentype eztlhto|)


Pintten otares sgchoker(J. 1

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

the sesves Ody. otsidete seoves


eiq. sendfedivect (Ma")
res.
eg reg getfeques Dispather
-fonasd Creg, s);

HHp fespmse Heades -


A))o lo) Refesh
2 Cornecion
se Cootie
3) close 12)

y Conterntz Encod)nq

Conto} Tye
expires
Last-modified
95 Jocahon
javax Servlet

Jntes faes - Servlet, Sewlelfequesterulelkesp


RequestDispacher, Sésulellonfia
ig
SesvetContent

C)asses - Gene aicSerulet,Sevle opuSatam


SenlelOuputStrean, SesvlelRequesbt
SesvletErupio, Uhavailable Fxcephien
Sesulel Conlextfveot

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

Eeques 1 JVM Threoad

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

pact of UKL URL


HoO to Creode lava Servlet prog soemoja

TYpe a Sesulet proqnam (Sourte Code) io


your direchoy D:/|Ty&(A)
his
Corspile this file by usi9
Javac SDemojqva classpathC:\proqram
Ales\ tpache Software foun dain\Tomcdo
ib\ servlet- apijar
J} ce
CHe a

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

http:/] 0calhast :80coseemal sDemD

ch pge

You might also like