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

Advance-Java-Servlet-1

The document provides an overview of servlets, including their definition, structure, and how they interact with web servers and clients. It discusses the servlet lifecycle, methods, and the importance of the servlet container in processing requests and generating responses. Additionally, it outlines the steps to create and configure a servlet within a Maven project.

Uploaded by

kp.at.workplace
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Advance-Java-Servlet-1

The document provides an overview of servlets, including their definition, structure, and how they interact with web servers and clients. It discusses the servlet lifecycle, methods, and the importance of the servlet container in processing requests and generating responses. Additionally, it outlines the steps to create and configure a servlet within a Maven project.

Uploaded by

kp.at.workplace
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 25

DATE

Servlet
Server
servlet container

Servdet1
Web Brov ser
responte Servlet2
DataBae
Servtet n

Serylets erver- side technoogy ied tota


handle client Tequest then pxocee Hhat
reqLest, Qenerake response and ive iH back
the dient
These respomse be static
dynamic wtipetia faebook toqin
static'-response is 8ar emeg cont
dyrani
+hat Bart Servlet Qce to meques t
Def 1 API
Serylet i an API, qererally ed to develop
neb -appicatin
AU the classes &interfaces related to setylet
API present in vax, serylet package
Javax.servlet

Def:Interface i InterFace
we alo san, serylet i
method wo
whia preient
olass lko implements servlet inder faceneed
te impleremontaioY to all Hose
method

Def 3 Program
Servlet isa pogmarm mlhich is goung to run
n rver meaning e

Servket progoram
orfac’ rlangey recbangle incle ’ ser input mve,
DATE

Ahat weh appicati on is to run


ser ver,) Tn Server We re to write
servlet claees and. theie
ta be
JsingreaueiA relrd nahenever here is
to hct prticWar
Serylet Then that partiiular serde clac
paodce neiponse Send back to
client
servelet ? class which aquie
Serrer
Creaking response. pmtouert
Toterface ’ 8hape Ki>
abstract mathod AreaPeri ner
class énmplemeuts Shape Cirele, Rectangle, Tria-gle
HTML Practico
Table
Seminar
Sche dle
Det Geqin End Topic
Mondag am
pn Intreoduci to XML
Validity : DTD 4 Reiar NG
Taesda ta Pm
xá! Transformaion
Wednesday X6L Fovaina Objects
DA

2)
1S
(17) 8 (1) 20
22 23
(25 26 21 (22
30 31 32
33 34 36

+ How does servlet


Sertet 19
progam whiah nuns
Deifest
requst url
Serylet
Fesponge
-6 Server
dient server architecture
Protocols
What pratecol
without URL, we Cannot send request. While
sending esuest, We need to follow Some
ralerUNe have to u http. After this, we
wiu send request to serrerHhen Servern wi
procese taat
A Server Can Camtain me

servlety
to decide mleh
particalar regueat
0e,, Servlek to call
means
or tge
'DATE

aandled
servlet contoiner, ServBet caotctner fll leive
request he requert mapped to wlich
servlet
Servlet Comtainer i take HTTP equait
to Cneate Tequest abiect
we dealingqwith Tava Applicalion
HTTP protcoso iE needto be
Canverted into Tava obiect, then hat Tava
obËect will be passed ta the ervlet.
servlet container willtake take aA HTTP
convert t into HTTe Servlet cquet
abieck
NOTeg Servet containr wil instantiate o cervlet
obieck hen gring to pass htte
HTdP Servlet Recruest oajet Sonto Serytet clase
rturn serelet will retunesponse
and it wil be in foxm af obiect
(HTTR Servlet nespmieobet
What 1S
Servlet 4 Generíe Sorvlet S

Seryle <i>

javax. Servlet package


implements
Servlek
We need to porovide Implenientatfom to
all method aSerylek'interface
DATE

D public void init (Servlet Conhig conhy


Tais methac
method Rs 'genenally caled to
initialize memhert of cate.
)
public void serice (Servlet Requot equett,
Servlet ReIpense merpanse
method oil take request
hespnse.
Gxplonation &
void init C
( Serlet Canelq config Servtet s
Caled by Servlet container to indiae hat being pload
Parametert : Intd serie
config
Thmowe
ServletExcption
void service (SeruletReauest req ServletReipoose res)
alled by servlet conteiner ta allow the serule
to nes ond to a request
Paraneters e
reg i the Serulet Requst object Hhat contains
client's requett
res the SenletKesponse okiech khat cant ain
servlet's riponse
Serslet Exception
IOEKCaption
'DATE-

public void deshoy C2C)


This metnod it alled to unload
Serylet classes.
publi Bervlet Canfia aetServlet Config )
lo qet confiurationînformaon
Cenligur dLim objekt oe fo Serulek)
)public Striog get Serylek Info (()
Thft meltod8% to return Shang
ging Serylet

Generally whenerer 1bidlding Servlet das


Ne ae not going a fmplenaeu Serulet
Rnterface
Weane ezktndina
Tosteadwe servlet dass
to GenericServlet clais

void destroy ()
Called b servlet container tondioate A
that
Serylet oeing ken out of service
DE

SrenericSerylet <c
'Generic Sorvlet' lass
Boterface
A
implernenting SerSorit
methods of Serylek tnterface will be
vlet
oheritod in enuieGerlek. a generic Seryle t
implemntatlon to those. netod is
provided excopt for' service metbod
service ( method
method Crenenic Servle clar
abstact
<i> |Servlet want to Creal
Vserulet.t.
<e<ab)Generic Serylet RcOmnendedto
inherit Generic Serutet
MyServlet clas and override
serivice C)method

Iougenerîo fe Generie Serslek alamg with serdet


Tnkerkale methode have Tnore method to
more inlormation aloout serdet
+. hat Protocol
Set of ules and aicalinea that govern
how devicesCmmuncate and ex chatge dhta
wihin a netuok multie netu's
Common languge thot wre deices (an
that ensure
understond each hw,slw
di fferens
>Netok Protocol :
TCP (Trars pmnission Conhol Protocal)/IP(Irnternet Protoco|)
HTTe(HyprTezt Taansfer frebocol) DNS (Dorsin Name Systen
FTR ( Tranger Proto
Applicatin Protocol:
a) sMTP(s inple Mail Tnanser Broke
SSH,ThS/SSL, POP3, TMAP
(paTE

There total 12metho Generic Serleb


interrupts servlet normal operation
public yoid inik ) hrows : servletExceptien
generaly used to instantiate servlet cla9
pubic Servletlontaxget Servlet Conteet c)
Retuns the refere nce to tHae serylet contet in
ohich tnis servlet îs unning
CServlet conte Coe opplication )
Returns
ServletCon tex ohject paused to
Servlek byinit O metho
publie Sting qetInit Parameter ( &ting nqme)
Equist
wWhatever sendike fosm iafocma ion
(namee-mailetc.)We can read all these
parameter

Parameers nae
calli method

Hae
name
perameter
Return Sting i PLia
Shing lizalom the valeac
tontai ningUparameter

A tmes poLrameter
method
caataioarameder
publie. enumeation <Sring qetInitlarametrName)
namnes Can be retievd

Returns 8
Enumerationi t iotiodject contata
name servlel parameter
o public String qetServletName.()
Returns name serulet instanc.
6) public void log ( Sting
Wites the specified meltage to Serlet
Ale

Shing Sting Specifying mesfage to he wntta

How to create Serylet maxen praject


Right dlick project explener> Select other
Seleot
CSearch mavtn)
maven pxaject Colick on next) again
click next > ler:
CselecE 1.4) Cick on Vep-achetbypewek
xt
next povise arfac-T
>inish
2) Open 'porm.xm]'> find <dependencies >, here oe hae!
toadd Serylet dopendone > Oa internel
search lo mvneporitoy Search for'Selet
APT' look fo
Java Serylet APE > qetvertion
4.0,1 Copy that : doperdency > Paste t ia
mexm!
fom.xnl" Sae the Aile After saving pyoject
wile build
3)| Goto Java Lurce?
folder, here we mglat net
retorce
seQ 'src/main" folder >sRight aleae prot
properties > Java bulld path > orter
O
maren dapendentes TRE
hystem brariesg>> Apply and clase. > Novo
see 'sre / main lava' Poldar
Rignt click p ect >
4)
Ocheck en > upodate profect
forece update> Ufck Apply
Ceateegister and run serylet o1-Create.Register.run.sa
fallo peviausfour skeps Aom Hos
Hovo to
to coeate
Servlet maven projeet
Now were goir to coeate serylet clase
coneate lae, openTava resoerces
Calder select
Aright lick 'srcmalaava')Create
ne class prouide clasedetatle
oublie wletCas extends
erletUass Genenîc Servlet
odd unimple mented abstract las where
method
( OverrRle ServicecO is adostract
hence ovem de serice c
puallevoid service (Servlet Reuueak req, ServlotRerpanst rel)
throwws SeryletExcapdicn, TO¬xception {

Aftercnealing nead to negister that


servlet ne
serelet fo register Serrlet, goto > project > te > maïn
> webopp > bkt 'wEB-Te'> web.xml>opeo ?t
<web-app>
<display-name> Archekype reated neh-applicaton</dispay non
<servl
Sservletnam SerrletName</servlet -name
<servlet-clar) Qualifi ed ClassName <serylet -class)
Same <lservlet
<servlet-mappins
<servlet -nanes Serlet nlames servlet - Name
<url pattern urlpatterg </url-patte rn
</ servlet-mapping>
<web-epp
-|- 'DATE

To un Serlet program, ight ick on proieck


Serre
(IE wofl ask you to which Seryer to run
Select Finish

PrintWnter :
co
class in Jaya ie. pat o
jnxa .io pevidt
pnckage metaods to write foamatked tes:
Methods far wikina datai
Print Writer provides a variety ofpint () e
printlnCO metboda for wmitin diEferent eindt
of including integer Floating
ata fleating paot
Dunabers characters Oand ating
E¡i print Cint ). paint (doale),d pxint (ting),ete
Read fom data GenericServlet (o-isp-form
The eq qetfarameken (Shing nome method i
oceyal volut para meker
fom the cients reg. in Contet of serylet
melho is benéiaid for extrocting
data Bubmitted toeugh HTML formy

Argumant i paratheter-nam
method takes parameer nam aJ
án
argumuntho's npnesmting
parametek alus
the hame
NOnt to ehica
The method retuns
Haat epreient sting
the vae ofspecified
pernmeter
retnfofr abent
absent paramter
DATE

The medhod retus null he specfied


parameter not present requsst
HTML 0,

ontrto HTMLforms, the paramter


narmeS are asociates! wit he
nane attibut f O Foc elements
<înput nane
-

paramter name
HTTP Servle & it'sme lhod :
Servlet

Generie Servlet Kc>K ab sern ce c)

HTTPServlet <c><ab ’ ab straçt


methadr

HTTPServlet is sstreact clase.It spesent


Tavax. Serylet

NorE
packo
HTTPSer&let-Ps abthact cass
though Hhere noabstat methocl în

HT TPServlet lessin Ja va st desianed


to be bae cass for cneating servlet hat
-henoles
HTTeTEqusat Althaugh Ort docan't contin
abtract method,it s marke as
abtact lasei beca 2 it not 0meant
be înstantiatec Tnstead derelopers
expected Create, subelaS
providing thcir oust etending
are
to HTTEServlet. nd im plement
for methods 4hey ant to overriee
NOTE- I e want to Caeate Servlet ta
handleg HTTR requnt particlarly it i
not recommanded t to inherit Genenfc.
insteac We nead to inherit HTTR Servlet
already have GenericSerrlek taen
de saeed to opt for HTTRSerrlet
CenericSerulet 4 HTTPSerulet Serves different
pupage TavaServlet API and ahoice
hetween tham Aapends the equiresutA
af web-application
CenericSerrlet 8
Genecic Serlek
clsthaut uandle requst
protocal in geeri neanned
I î:nst spectic to HTTP
HTTP can be
other protols well.
HTTServlet e
HTTPSerylek is Subco] o reneriç Serelet
that Proxidos specific Suppoyt for banding
HTTP tHut ad response I includes melbol
Such as doletat do Port), dofuto, do Delete
fox handlina different *HTTP neteadt requeit
Qnd response
HTTPServlet des'qned to simlily he
derelop mant a wcb- opplicationj that speiicals
deals ith HTTP, It obstracts away
details the HTTP pralocol making
easier to work with aigherlere) Cotepts
Quh equest paramett, sesshen
management and pattens
DATE

Metholr oP HTIRSerylet

clalcek HTTPServlet Requeet neq HITPSerdetResponse Te


Thi method ueful yhen de aling
HTTPqetequest, Data will bebetehed to
url, esutins in low security
doRost HTTPServletRequest qHTTPServletResponse resp)
Data will be peustecl into HTML laady, eniuHng
belter secutiby
We nmouy eplace Serríce C) methodoith
dolet 0 olo Post c3doTace)doPut
odoPost c ),9on
but elesteaat dacteoy ) method wil
only be execulcd
ony
To HTTPSerdet dasekl) 4 dofosto designed to
HTTR GET and PosT equet
handle
The
e
main differenee beluueen Haese
HTTP
espectiel
methadt
Request, they ane
intended toptocess ond Huey handle Reguost
Requast
parameters

#doetc)
1hi methodi
called
uSedto
hen
handle
elient
httpget
sendi a
Cquest using HTT
Crek methd Ty pically getR
fox aperatiag thhtdo
neiReguest
not uave Side efects Suoh
information Sisplagian resore
retieving
Tn get eueat alta appended
qupryparameters
DATE

These parameters are ViSble


URL itrele
doPost CO
Th method is used lo hande http PL
requet. Tt i calledl ohan Posk
olient sends.
request uing HTTP Post
post metaod Port
oten ied fox aperaticms that hat
<ide effects Such as Submitting form
updating data an server,The data
doto
sent the the requeit makirs
it more Suitable larqo domount
data. Tn postt requagt, Data not viible
URL centn

NOTE By default <fonm> tag has get


method e , To use. HTGOOst type method
atibute <form meod= " Post">Vfon
Paramete

Query parameter
îo contezt ol servlet vefos
ralor
to e paro meters that incude in th
URL of HTTP Tequest
These Pammeters are addad to tho end
4he VRL aftera questin aack and
questionpaack
Separaled
CPuery arameters mmoay ed to
Send data from he cient sehver
DATE

Aekzicving quy para mekern i


Servlet Can retiere y paramelenuttng
HTTLServlet nequest abject.
The qet Parametercs R wsed to retieve
Nalee specific parameter hy pzauiding
name

ormat parameters
Query parameters sppended i URL afler
qeatic makk ( 4 mullile patameters are
separeed by (&)ampersanod
t Webservlet
This standad annokaicn in J2EE for
Serylets.
declaring is a partafo then Jayax. Servle annotaion'
paclkage

The value albibute specifies taehe URL patern


to wlaich Serletshould respond
Case Serylet mapped koto tae URL
pattern "page-a"
Tais annatatin porovdded cmvinient
to Serylet without the need
explicit entries 1 web-xml
TE i commonly wed in modern ava
web Applicatons
DATE

Life Cycle Servlet :


of
Facm birth to death ofcervlet,all
of
are taken Care by aweh- container operahiza
Step 1 & Load Serulet
The 1St
load
step
seruletclass
serulet
inta ifecyck i
The cdase loader reipor for loading
Servlet ioto mamey uhen serylet cass reiveg
fistrqu
requeit onwards it wiU not load
agnin.
Step 9 2Careat iom nstance i
Neb ootcinr wil caeate instancefor
Servlet clas using laich Can a Ccess all
method object
Dhieck caeaton will take place cnly ona in ente
afecy:le servlet.
Step 3 a Initialization
The web cmtainor wil initialize the parame
ter ongtanca
o ko. aliag init o method

NoTE& AU abore steps will appen ny


Servlet's tifecycle
Step 4 : Invoking Service C) method
Web- containeY wfU invoke Service methcd
The Service c) ethod wi be invoked fox
every uent
|DATE

Step S E Detoyy
Destoy the ervlet
web contaier wiU invoke :y)metho
cloy
loefore
wi lbe unload' ng
destroyecd.
Sérvtek clas Vservlet

operation w'l
serylet' Ufecycle aappen any mce

Welcome Tile ist


whenever nee
CAnd
that
want
time we
ane

need
launchiag
to
web-applicatico
Specific page t o be open ot
moditication
in "web. xml
<welcoone-ile-list> taa
tag will aelp to set which
needs to opened vohen a n applicatHon
launched,
In the weleone - file-ist Can contigure
multiple bueleone Ciles
<web-oapp
<welcome -file -Lists
<welcoe-Gle A. btmd <welcone- ile>
<welcomie- file B. htm <wel come-kile
<welcone- file) Cihtml <welone-Pile>
</welcomae- ile-list>
Klweb-app e have multiple elCoYme Cile îo
welconue File isttwi wosk f-lse
adder, TÆ page A,B.andC not auailable
hen wu Hhow Error 404 page not found
all Specify welcoefile lisk
defautt indexjsp
when 0 POge wiu open
an
web-appicaEon launched
abgolute path, elabive path
OScape seguonce characher DATE
clag? oading proces 3
-

se case welcome Kile List :


primarily sed to provide
\s
default entry paint
4 eh-aeplicalion andig
’ Default landig
The welcoma Alelt lows to speit
monee ile that shold be
a
Com sidered
eser acceSeg
adefault
landingpages.
root URIO wha
forr eg. : I we have indexihtml Bile
welcome files accessing
http:H example com wbuld displ&y the
index.btml

It belps in coating uier-fricndly wRLvRLwithout


exact AI ame î nHe e URL.
specilying,
e http:esample . Com honne htil we can,
Horme. btm a a welcome file
conligurt
and ser can accesr i via bttpiIexampk.ond
Load
In
tertup
Serlet baied )eb-applicotion toe land
gtartup elerment
elems in web. xm i ued to
Hhat serylet &hould he Loadedl
ihen' Hatwehappcation tarti, rather than
sAitingunti) the Serrlet Rs finst aCCested
> Purpose :
Load on startup is used to ensure' hat Serdet
's îniialized
he
ond its initco m ethod i callel
when web-appli caon starts.
I
- p g TE

You Confiquration in web.xm!


locd onm startup for
servlet 9n Specity load a

web.hal by providing inteqer val


K'servle S
<servlet-name YounSerylet <Iserrlet-name>
<servlet- clags com, exa mple.YounSerylet <lserylet-da3
<load- cm - startup) 11 K load-om-startup>
S/servlet>

Tee integer valee an <load- m-


ndicates Onder which
startup tag
Servletaheu
be loaded. Servlet witla lower alue eloaded
Airst Here we Can not -aire ncgative
nly acepts postire
> Initializatim Orcer
Servlet with Ioxwer load-on tartu value e
loaded and initialized before Servleks with
higher rder.
TA multiple Servlet hae same
Sameload-om-startu
value thewebcontainer determines the ondor

>Advantages i
Usingload'-m-startup
Serule
can be beneficia) Aor
Lhat
need to perforsm initializoton
task setup es0wrces when applicatic
starts.

Use-Case
Tnflfallios databo connections. Establishin
Conmunea with lexterna resoroes
DATE

configurakim solting
<lald-on- startup
We- Ca ses
utilizing
used
Tn gummary, oad-m-stact aponderol to
Condral he 0nitialzaton ensureg -a Sere
in a eb-application. TTE wree hat
serylets are loaded and intialized wben
the applicalion ctarts AL hem to
pertorm ke sks setup tagke belon
andleng dlient eguott. Loadl-on -starho
Hhena pariculac
Secvlet wi be loaded l initialized onu
hen egLnted.

Can we lo load-on -startuo using annotaio


Yes Can acbieve laadean-startupking amatakon
The a Web Serdlet annota ion provides Uload-en
attbute hat allos
startup.
specißy the onder în wtch Serer chould be
to

aiafzed duriog apicakion startp


02

@webServlet (value :"your- wrl- pattern,loadonStarhupai


public clase ounServlet extends HTTPServlet
syowr servlet code
-
IDaTE

what happeny when we qive negatie


number
negative value fore
stertup
generally cMsidered
Servlet confi uaion
invalid and
Oesule unpredicted hehariour.
allowin
negatie
re

valee
sCenarios Hhat mitht hoppen2
0 Serrlet comtaàner expects poiti ve integer
waleees
value
<load-on- startup> tay
in <load-onsBartup> TE negaive
prerided it miglat be ignone
treabed as ernor énterpeted
unexpected bethari our' not
standardizei Cacoe Servlet -containers and
conlainers
different
walies ALfferealiy migut handle negaie
zero innalie :
vaue pot valid value in
<load- on. stactuptaqit expecked pasitie
inteqerssEtb alue is provdod it might be
ianeoned. treated as
Bhaviaur
an erro 0
intepetdgl
differen serylet
eantainer

bestprackice to pmroide positive


Maleee
DATE

Ratt Dispatcher
Request Dispatcher
The Requast Dispatcher
Servlet prorides way Tnterface%
to
Tequest
indade
from fosward the
rvlet to other seryetvle
the Content
resources ( servlet, JSP, HTML)in another
LE is
mainls wed fe Ahe respane
duringrequast procesiog. erver-side forwar
the basically helps
where to where
Servlet to othor Servtet
Servlet to
to other TSP/ HTML
OR
tram JSP to JSP
OR
rom e SetoSerylet

)uolic
Dpualic void forward (Serylet Request neguat,
ServletRerpmse respens)
For a Request Dispatcher cbtained vic getRegkBapa
snet Request Dispatcher (O, the Serdet Reguett abíeck
VbasPts path elements and para metert
adiusted to math the path of target resurtc
Cor ward shauld be called before the respaas
has been Committed to cient
Forwards request from sevlet to gnother
(selet, ISP Pile, or HTML Gle) on thR Server. resoure
DATE

Porameters
request ;
ServletRequest obËect that nepeseuts the requ
helient makeg oe serrlet
Tesponse
ServletRespnJe
respomse he
obieck
gervlet
that
etun
TRpresents
to cienk.
the

Servlek Exception
TOException
TlegalstateExaption
)public void incede CSerelet Requeit requsk, Seletfupn
mesponse )
Incudes the Content oea nesouce(serulet,1Se, HTM
Hhe response.

Servlet Requst object contains ient'y eq


hesponge
Servlet Response object contains Serulek's espa
Thros
ServletException
TO¬xcepticon
How to obtain request Dispatcher
Tbe equest dispatcher can be obtaioed uiing
getRequet Dipatcher) methood using HTTP
letRegut nbjeck eference
'DATE

RequastDispatcher rt questDispateher s reg


Tia method takes relative path of eiou
as an argumant

Suppose you have Sevet A, thot procet


Proceli
data, tthen forward the equeit to anotur
A a displag Hhose results
Serlet B This heet
modularizing
Concem
applicakicn lgic and

forwarding is used auhen you want


anotherSerlet resouUce Uto andle
the

» formarding
entiret
Foyardis achieved csing
method of OrequestDispafdher
forwarde)

NoTE&After the forsard,the


miginal Serylet stops and Control
tretslertedto clos tinatian Serslet.
proces.
inelude (reg, regp2 gouwant to
Lesedh
include te eorttret content another
Senlet re So rce in the eiporg

You might also like