Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
121 views20 pages

Dynamic Servlet Handling Guide

Uploaded by

Pankaj Kumar
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)
121 views20 pages

Dynamic Servlet Handling Guide

Uploaded by

Pankaj Kumar
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/ 20

elsssuste

UNIT:3 Dastaath
Date
Page
Nandom.

a lb bowe and
Afaua class that suns en HLgusts
dnamically handlclint dt is useol

A uch abblticatin s an ab: accesitle sum the web


(Jawo Semve Pages
4 ueb Comþonent is a Aettuare entity hat hunu bna
keguut
web senJ dynamicaly tandling chint
Servet H
Reqyest Kequet Serviet ontainen
Neb BrOWSeN Web ServeA
*Rejonse Rafponse senviet 21

Dalabae
Servelt Achitectune

nlenface) dechmelegy enablbastheHTTPweb


"CGI(Comon Graleuayertunal
Ayer to call an buogram anc
segueat into to the ertonal tsogam to þracess the request

DBetex fotormance : As it cHeales a thyead for each Hegust.


D) Platorm-Ynalebendert and fortability : bcz ilt usu Jauo konguage
*Abplicatibn of Seuilet: ).
D Read the exslict data Aent by te clint (browses
) Read he mblist HTTP Heoest dat dent by the clentt
i) Process the data andgnesate the AAlti
i) Send the erplit dalalie document) and imt
HTTP rwponss to the client.
*A ucb tontainer is Heabornstble to
to apantcular detet ant masing
ensving thataURL
the
URL Aiguaster hes the Coect aces highh -

Servlet can be catd using uax Seutet and


autx seultt hitf þackages
Seudet intoace busuiducomnen behauiss to
al the seutots , it deline metheol that al sewet
must implement
" hexe are 5 nethbds in Sevef Inletacei aSonvle Tnisga

inikalijs the sewlet? Htþ Sexvlet clas

-þrouide Hesbonse tor the incomúng Hegist Login Seet


i) bublic Leid destey()-fnyoked only ohce, indieakd Sevled is ase
1) gtSolt onti) ekarns Ohject Sernlet Config
ysuchã oayight, witn, verstin, et
* 1emeric SeAvlet Cas
Gtemexic Selet clas implement :Senuctt, Senuielenhi y
and Seialiyable intonaas. dlcan hamdle any tt
Lsf Hugust do, it is bstel- indebendent
Metháds
bublic ueid intl li,i):
ALL 5 nehods e Seult
"pulie Stáng gt nitarameka (Sting hame)
public Shin gc Stmletlame) xeten name
he Benuiet sbfete
("'Desheyeadetey)fsoP
) ueid bublic
<Ihtmi')}2 </body ) ("
þint out:
</b>
")DNandan helo <6> l'print Out
body>); >
<html< ("pint Outo
qethnieal); e' out ultten þrint
Sevle aenerit va Oue
<a) þi("
("khn))( þirt
body)"3 SeruetExcelionQue T0Expion, hrous
ves)eeþindkaier
iterOyes"get Dut= (SRhg,
Res nua Woid bule
on SevelEveecion, ongig)
ous. init(Snvellanig
thTO uod bublic
SeieRra
hes) Sles NBid Bublic
Seuet imSeveþemenk Dashath las buiblie
das þublie 3 el jawax mport
Benvl:X
ie exlends Dashah o-*; java. imbort
ojServlet (avax. Import hatejae Lnplemenling
todet
y Sendet Grenenie inhexitin
the i)
Serulet HTTP Exterding
ntenjae Snuit
implementing D)
erulet Caeak
a uays
do three eJhnee
lace/do
e ptiondo doteadclo Pest/ do 4
keponu d6et{(ltp
Ht,reqkegest Senwlel usdbootecked
Beice( uotdbrokckd
Seuekishonk
)
): (euletkeguat
ruq, enuice Leid þublic
: do
do Post, Svializabe such
a mitheds
imblementi
ecifeleTzace, prauicls dt doGiets
http doHead, intitae
clan
andl Gumericseat extends
the lass Sexulet Htb
Clasi
KHtþSeNlet
classAte
Date
Page.

New
2
Ah Hte Aniet's lie ycle is conbslkd by the. 3.
lueb container Whee it u debloycd'
hnhenL ane three states o, o Senvlet: Neu, Keady, End
Svel Clax is oaded : The Servled can is doaded
when Arst Heguest on ServietçHeceived :
&) Serlet instamce is created: Ihe selet n New
Atate hen denulet inatame is cuated
3 nit muhod iinuekud ' nit mehed is sed to
ntaliehe sevlet Atea invaking init(),Sniet lomes in Ready.
4)Seruice mehad s invoked: he ueb centain cal the
Souue mehed each tine ten hugust fp the envlet ia ecciud
soulet
5 Deshoy mehodu inmakad: dt usus
5)
hnstbnce trom ttedoice .

Serudota
The Seletkeguest Snteface is usud to hamdll clint
uguat
"buiblic Objct getftiloute(Staing nane: Reken the value q the hamed atibke
bubli int ontentlergth : Rehurnu the length of the sugust body
" bubli Sting geltonkent Type : Rekms MIME ype Gf reguut bady:
bublie Stang getfummekor (Sting name)
þublie Shing getPrttcel ?Reuns the name and esvension of Astecel
bublic int get Rembke Port: Rekuun the IP þoxt the cliont
* SouledReabense htenkare:
Jhe Souktkesbense nttace dfeins an shict to hets a
Semlet in sendinga tusene to the slent
Seruldt
alAs Mate
Date
Page

Methocds.:
bublie wd flushBuAen: foces he Content in the butor to be wri
þublie int qet Bukhel sie: Rekun the aclual buter sye.
buble Sting gelCantendTyp:
bublie Bantabitee
bublic watd Hestti ceavs the bufer az uiell as Aaku coole
uble waid detBuerSige (int Sige:
Ex Reguest to take uoname passuoYd ! HTTP Sevlet
/jndex htm. 7Demo jova
n<form acion "est method H
"Pes : mpord josa fo
her Name: Kinhul tyhe =kxl" name:"ur's<b»mþort owaxServlet:jA
hssaord KinþuB Jye: Pacswond"Posswond'Kbr inpot jauar Servet ht
Kinput bype
<Senvley) Yeg, HPSrak se) throw Senvletexchte
(Servled-hame) letK Ise veb-name) TOEXCepions
Tesfponsei set Tondent Iype 'kxtfhtel'
(seiel-clau) Demo (serviel-dos ) inhalrie bu= Vesþanse -qelitul
<Sernt)
<Servlet- mabhing Shing þasuoad= Yeg. gd Poraueke 'kaud
(Servlet-nam) lest (seavletnamme)
fnalys puw clese3
</Seuled-rahing)
Creating Selet Examble in Ecibe sntit th
JDBC oel
Eclibst an bben sowxce ide ter deuelehing Jauat
and Jaua£E(J2E) applicatin
Dbu ned do duunlnc the eclie e fo. Jaua EE desbe
) Geate the dynaie eb project .
Chiak on Ale Mlenw ’ New >Pgucd> web dynamic web prgjec-> name4
adkssMate
Date
Page

9Geale the Sexvlet in elpze IDE ! +lon ’ Cxylore the Jawa ResouYce ’
ight click Oh Src’ Newervlet name >nchek au cheekbon
ecest do GretC) het Anih
3) add ix qile in ecise TDE: hght clike on rojct »Build Aath>
ConhiguwieBild Vtth ’ lbraiu tab ’ Extermal JK, buton ’
select the seet - pi jar fele noer tomcat/Ub ’ Ok.
4) Staxt the dexuer Qnd debley the þugict
oht Click on hoject ’Run As Run on Sewer ’ Chee tomcat
Soruen >nent addAl >inish'

An chjct bf letlenk'g is ceatd by the web kentaine.


er Sach eulet Jhe oe aduantajc is that yeu con't ned
Nethods
Stinggetnithametr (String name)
Enumeratitn getnit Aamileinames)
Sbing getsnlelhame()
*Seubt Chaining
Ud in oHde, to FoRARD OY INCUUDE aHLquest em one
Aonnet to ancthen Regyest Dispakches intexface brauide tue
mehocl Reguest Dispatches foroad (reguests Yesþone)
Reguest Dispatche" nclude (requn, hepense)
AServlet Chaining: fowand (requesty response)
Rep. foscingSenutet 2
Iclt1deent Roquest Servet
Restonge enenaton
Sesvlet Chaintngt incluote (requests hponse)
cliet Reguest Regustfasag Sewlde
Servell

Response
Qenesion
legueste
JSP Atands for Jaua Sewer Pages,a technsogy which
Lallauw the llsy ceation st houer sioe HTNL þags
JSPconsist s bth HTML tag1 amd JSP tag
Featuses f JSP:
DHigh bexyormamce and easy to maintain
5 Riductin in the ength ef lode
i Conneclion to Databae iu easin
MPouulrecl by Jaua- aliesto all Jaua APIs
JSP Blement
oJSR elementi can be duidecd into 4diheent types -
DExprenibn Suiblets 9 Disecies 4Declasatios

JSP So«istinq elemend fusuide the abilty t tinsent


jaua codeinside he isP.

Scuitet tag bejesien tiy " declanaton lag

gaes e cocle n JSp.


Syntaxi Z jaua Seuce Code %>
exi- <htmi>
<body >
<% outrpint ("alelcsme to isp"); %>
</body>
</htm)
Nete: Semicolen at he enol et bcristet
Page

ISP CaptLIAONhis tdg to sutbut any data on the qenonted


he can se
aukomatially, cenuntd sbing
bage- JheseAata aie autbut
and brinttd en the shlam iCh="HeloWorld"%)
SyntaxK®= Stalement >

XISP declayatien tag:


Declaation tag u a bleck gaua code fo delaning
clas uide uaviabless, methodi and clases. he code
a i t t n insice he jsp declanatien ta4 iu placecltioe
he Beie l method f autorgenekated deet
Syntax: eld or mehod celorakon %)
Z frd
&x: <html)
< head)
<tAte) Declaration tagExampe </tHe
K/head)
<bocdy) %>
<%| Sting name
<%= 'Name Isi"+
</bocdy) </html>

t7SP dinectves
he ispdinectiues aHL Memagw hat tells the eb
Conainen ter to translate a IsP page into Conesbdig
Auet
"Include dveche
tagüb dheclie
Syntax &f Direchves:
<%0 diectie namne otibute name"Vale">
1)ISP bage diectiae.
he bage diactine defins allibutu hat asply t
ntin USe hage. "%>
Syntax: <% @pag athibuto =" Value
Atbibutes bage directive
inpost
K2e pag bugen ="skb/rone "
" jaua" L)
sEYgnokned : sbecify hehlr apresion il eYalaled or ng.
+age Eneoding aizbrorhge
) JSP Tnclude Directire
he inclde dinectiue is sedto ncluce or Cshy
Syntaxi K% @incluce file ="olue" %>huValac
the SP file name whlh neds to be incdudel
Noke- dtcan be ised anywte in the bae
ei <% include file =

tiglb diectiue allous nto ue lustom tagt in


S. Ehella you to cleclae tustom tags in n

Bx: <%e kogtbunie "hts:/wm Samjle om /my custonlb


prefix -" demotag'%
<htm Kbody)
<demotag: Aaleoe t
<l6ody>/htmd)
Page

Jhe JSP Stamdlaxd Tog libray epluesent a set o tags


to dimbljy the JSP dualsment
Aandages i DFst develshnnt
) NO need to use soiptlet tag
*JSTL Tags
ISTL

URL managements Haus lentsl, ete.


Ctout iJt du blay the Heaut of an expesion
Ciimbodi t Retues Hulative u absslte uRL and diublay the lontat
C:Set
: C : emere C: CondltHonal taq.
L:C: Choose, C: kthen, Ci othenuise ’ Simply Conclifional tag
L4C1 for Eoch ’ Bagie iteraton tag, bcipoiam: Qdds karametet.
4C: redirect

a JSTL Functien aqi


Jhe JSTL fnction ueuics a mumber st standand
nctins, mest of huse fenetliens QHe cemen stin
manibulatien tunctions
ni Conkatns 0+ Test tf an input Ming containinq the substing
fnt ConkainiIgnore Casel)’ "fn: endsith )
uintenpheked
+fni ecape Ximl () +eAcabs chan hat efn as xM;, mankuj:
Stantllh)
nt index af ) fni tom ()
fn3 tolsuer Case)
3.7STL Fouraating tags:
tpusuine dispot fr mesage fomating s numben.
and dat formating'
Taglil :
f: se Nambey fmtttine Zone 3 fmti paze Datu
{mt 8e Tme Zone fmdi Bundle fmtimesage
mdiomate date.

4-TSTL XML Tagei a JsP-enti


f manipulating amd riating xM dacument

X? Cheose X° when
X3 Hheruise

5 JSTL SQL Thgs.


<2e tagib Uni=" hetp:/l java-Sun om srlisTe/sgl"prgr z

S:SotDalaSouxce ’ U3ed tor creating simple dla Jewce

Sl: poam
i date anam
: toansacen
essuste
Date
Page

Dala
Documert
SChema Mon kub

Doaumort, is a combination sf data and markup


Markups descnibes the data in he doumnunt and how
sheud be tntnbretl.
* XML
Extemat ble Maykup longuage AStandand fr data echang'
Desigred to describe data
4 used to-Sep ate cha frpm HTML , erlang dato
store data Shane data:

Adsantages: D')s0dvankages
Redundant Syntex
D Humam Teadable : XML Uses Sinple text-basd
tormat
iD) AUo Valsatien : |i) Vorbose: Xml fle Sge
im)Exensible :lustmtags can be eated incraases Cet

<?Xmd Vension=1·o' Proloue


<Person> 4 Root Eloment
<Name> Dashrath </Nemmes ) Document

</Person>

Prolog : Aþad st XML documont hat becedes xML data


)
t nclues- A declasatfen , gn optonal DTD.
elsssMste
Date
Page

) Elements: Baic unit ot an xML docment Jt is a


Jpaical structwre tn XML hal ii delimibd by a
Stnt taq amd an end taq: 4 consist 8f pat -
KNtynes Dashaatti </Nmes
Slant Tag Content End Tay
Stant amd End Tag should maBeh amd iucase Bensitie
) Atotbuty : Prouides addilional infomatien
Sbecilied in the 8ant tag e4 he clement Haue
a kiy- Value ban Atibcte can hae only Gne Value
Flowes CoOR = RED RaSE </FOwers
Atibute
Name
Attibut
Vallue

iw) hell-famed XM Documexnt


An XML document is daidl to be well-formed fit felews
W3c
basic dymtan Hules dhecifia for XML byelement
Must hae Gnly one 0ol eemint "Eey must
haue a clesing , tagElements mst be þropenly restid
tXML Tree Shuche
An XmL document has a sefxM descristiue Shrectwne- t
foma a ree shruchue caled ree.
Tree Sruchute
Note:DoM þayge Yepresends the XMLD0cunent in ef elemest
XML Tree Rules - Uzed to toune but yelatonshi
ythen Aiu descendant fB
Descondams: f element Ai Contained by 8DOument Tre
i) Ancstors? Do wmen
XML D0Cumen Always ane YoDt
Kcowntry) etement
<Cname> Indi </enames Caunts)
<apital) New Delhi <aptJals orolened
Cram
Tndia Neo Delh
Date
Page.

¥ Valid XML Doumend i il H- s l formed,


An XML decument is valid
DTD(D0cument Tybe Defnation) , DTD and XML
Jeclanesa shuctunes
achemas preuids dscnibtiens o deumint

lgal building bock s an KOL doument


DTD ns the docwment
dtts a means do aidati xML
AK! DOCTYPE> eloment is ed do create a DTD
The elamend can take digesent torms
<!DOCTYPE 0oname lDTDI)
<3 DOCTYPE 0ohane SYSTEM URI)
detf URIS
K! DocTYPE Y00tname PUBuC

ntenal DTD: Alo known as inlenal subset


dechraton] >
<!!DOCTYPE Rootname Celement

bxlenmal DTD: 44o knouen s eoctenel Aubsct


a)
declaratien lisin the external decumont
SDoCTYPE Book SYSTEM "Outut dtd'
Example
YXmL Version ").o"1>
SYSTEM'embloya-dtd'> extenal DTD ile
< DOCTYPE emplyee emplaye dtal
<emelaye name)
KIElemerd empleye ist name, las rane
Kfist name) Dashath <fist Kelement frst name (# PCDATA )
astnames
Klast name) Nandan</ K'Element last nae (tt PcDATA

:
*XML DTD uith entty declaratonampnsand
has three arth : An ( B,An entt hane
mtity
A Semitelon (3) .
(!ENTITY enthy ramne "entety velue">
Date
Page.

Chaactn data,contain he tant


XCDATA: Unpased an Xmb aoument
which iA met pased tsthnin ane mst teated as
tas insides the CDATA tont
markup and entitus l net ersanded

PCDATA: farsed chatcts Daa dt is tha teat based


*
peDATA
CDATA
XML Version = I-6"?
< sam
<DOErYPE employe SysTEM"emplydta'>|kemploye>
<emplayees Kfrstnam) Dashnath (/fot)
<iCDA}A Ya
ashaathK/ftnamme) KlatnamyNamden (lbtrom)
<rslname)
<lastnam) Nandan (/letrames Klerlye)
Klemploya)

XML Parsesk
XML Paser s a Aeftuane ibryoh backage that þrouides
abblicaten do wek
intutces fon clentParsen uith an
XML documet XML Validate the document and
Lcheck that the clument u wel formattid
APT'S
XmL XML cCient
Dacumerd Pansen Alication

i) SAX
classMate
Date
Page

4SAX Simple API for XML)


ASAX ParBer immblements his API i an llend ban
Qnd less intidue

FeaBures :
D JH doesmt Creale any intenal strchre
i) Client doesn't kneo hat methods to cal, thay juut
Ouerride the metods of Aer and place the code
dt uamcuent based þarsn

Adbantages DisQduantae
huge doUmentd
2) DOM Documet Ohject Mado)
A DOM deCurment is an bbict which Contains al tu
Ble a tree sructue DoM fanser inplement DorM APZ
Feakwnes:
) 44 ceats an internal shructue in memey
i) 4 defines dtandard ay to acas and manibulat XML dy
i) DoM paAen has a tree basedsbcture

Aorantages Diaduantages
i) API wy bimble to we At is bleuen
ir) 44is reedUhen handem
oces touidely debaatd
ot of adument ia heguied
elAssMAte
Date
Page

DoM rebrewnt table like ttis


TABLE) |(TABLE>|
<ROSS
<TR> <ROWS>|
ITD> A<7TD)

(TD) C </70)
<TO) DTD) kTD
</IR) |<TD)
</RONS)
</TABLE) D
|A |B

SOAP REST
DSinble 0bict Acces Rabol REbresentotienal Stale Transter
) SAP s'a þroBoce tREST san architectna style
ii) t s s semie intuace to t uses URI to eshee busines
abese bustines legic
decwity measure
)dt defins ita aon Secwnity|3A tnheit dihenent
v) SoAP bermits XML data TRESTbermits dato format
Hotmat only -Plain Text,HTML, JSON , ete "
vi) Les þxeßred More preferred tam SOAP.
Vi) JAX-WS isi the jaua API JAX-RS is the faua API fo
RESTA ueb snuices
*Some iab" TAX-RS annetatisne:
Path 9 6¬T@PUT, PosT
DELETE Produce
* RMTRemete Mehecl Tnuecatien) mechanism to
he RMIis an Aer that buouides a
lcneat dutributid aplication in jaua beken he
he RmI bides emete communicattin
asliatiend sing tu oyjcta Stub and skleten
achinl A machine B

aller Remotel
Loject
Skeleton
Stub

Tndenet
* Stub: Zhe stub is an sbject , act as a galiuay fer
the client bide hen the calln inuste
mehod en the stub ghiect , it daes
a conmectibn uith Temoe Virkual machine (JVM )
|1 mitiates JVM:
2 unitu amd tansmit (mashals) the barametu to
3it wuait tor the reults
444 Heads (Unmashals) he etusn value o trceptien
caller
s t nally Hekwn the value to the
a
*Skeleton: Jhe keleton is an cbjcct, acs as reguerls
galeuay foe the deuen side When it eeeive
mefhad
"b l reads the parameten for the emdfe
il inuoks he methsdl on the ackual hemste Gtject,
Caller
3"it writ And trasmia (mashals ) the Yeult to
* Requiternet tox disbcbutid aBlicatin -
he bbicatien md do locate he remetemeMed
4ned to brouiole he lommun uith semste Bbyiet.
hese
do load the
cles
fcahes defnation fo shyict
RMI hs all
alassate
Date,
Page

*Tava RMI Exanple:


Jhene ane 68leps to usite the RMI HBqIm i
slep 1: Ceate the emste intonface
sleþ 2: Poide the imblementatien Gf the emote interjace
3: Combile the imblementatien clau and cneade Stub
and skeleton sbict uing the mic tosl
4: Stant the tegisby áouice by Tmiregistay tl
5:Creat nd stait the remote absetatibn
6:Create and stnt the cllent abblicaten
Acdet
pubtlie int addintx,inty)
client Sere
Adclen
|ProxyObjecH implemertatien

Codes sBep by steþ :


imbort jawa . Ym/. X3 import jaua m. Semver*;
þublie intajac Adder extends Remete_
þulblit intadd ('nt X, inty) throus Remtt Exceptfons?
public ala Addenkemst extends Unicast Remate bheet
AdderRemste ) trouu Remett Ecaption Sper();?

SH)3: Tmc AddeRemete


S4:
YIeglsby 5000
so00
elassmate
Date
Page.

Siebs: bbie clan MySenwer


psVM (Shing TJ args)
Adder Shb = new Aader Remote3
Naming: Hcbind Ymi:l bcalhazt S0oo| Sono', stus );?
atch CException c) S.st(e); 332
Seh6: bublie class Myolient $

Aden sb= (Adder) Naming -loikuplmd:l| lxcathesiSoo/ono


atchl Excepton e) <soP (e)sy3

You might also like