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

Advance Java Servlet 2

The document discusses the SendRedirect method in Java Servlets, which is used to redirect a client's request to another resource, either within the same web application or to an external URL. It contrasts SendRedirect with server-side forwarding, explaining their different purposes and behaviors, particularly in how they handle client requests and URL changes. Additionally, the document covers HTTP status codes, ServletContext, and session management, including how to track sessions using cookies and URL rewriting.

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)
3 views

Advance Java Servlet 2

The document discusses the SendRedirect method in Java Servlets, which is used to redirect a client's request to another resource, either within the same web application or to an external URL. It contrasts SendRedirect with server-side forwarding, explaining their different purposes and behaviors, particularly in how they handle client requests and URL changes. Additionally, the document covers HTTP status codes, ServletContext, and session management, including how to track sessions using cookies and URL rewriting.

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/ 14

DATE

SendkediectC:
The Send Redirect (3 method in Servtet R
ese to reolirect a clientls request to
another esouce, eher witi Same
web-aPplication external weh-applicaton
Cexternal url 2 TLismehaod i part f HTTP
Servlet Response Interface (HTTP Servlet Response <O)
>Redirecting to another esoure
The
mdiect
SendRedirect c) method
nesponse to
sends
sends a tempor
thelient
the clients browser to make instructnq
nenm requert
to the specified url
SendRedinect (" uurl !)nterna ttnk ke
eip. agmenk gateuca
uRLs
The URL can be relatine to curre nt serrle

URLs
absoleutewRL
RLîncluding externad

send Redinect ("/context Inewfagehtal); /Retative url


resp.sendedirect(" bttps:/| wow.exa mple..com/"); |Ab solute url
Citot -side Redirect
Unlike Server-side forvward(request Dispatcher.foreun)
cendRedirecte tigger
Cient's browser
a new requesls from the
'DATE
Requast Parameters 8
Kaquost faraetenCan be iacduded n
tho UL and wiU be avQilable t
redinect the resburce

resp, send Redinect Chttps: l/ww.google.. co. in /Searhpg:


+Socia-ham
Carmm Mistakes
Attemptin touse nequas tDispatcher.foar
after gendRdirecto in the same Equsst,
lead to unexpected
nesponse
behaioui cycle may
These tuoo methode serves diFFerent putpos
Conctderaion
sendRedirect (o when you miant client's
brocer to initiate a -Meu equest to a
ditferent wRL. Re carefl about ÜRL ÜRL path1, A

Cantet path and whether URL is nelative


absolute.
P
eatune RequestDispatther
Forwardo include c)
send Redirect CO

Perpose Used for server-sfde forward Used for client -side


and include operatfons redirection to a.new URL

perates
Entfrely Server.side Ini<fates
client-sde
request from

ORLS VWbrks with internal uRLS Worke_with both nternal


within Same wcb-aplication on external uRLS
(witin o outside web-appl)
fYOWSer VRL in cients_browser URL in client's rowcer
VRL does not change changes to neinected ueL
Reauest Alows Lshating of request. Request Atributes
Atibuts ottribtes betseen the shared betuoen the
SoWre and destinaian SOurcece and dectinatfon
Perfremanei Generally faster as it Invblves additi¡na round
involuesinterna processing tips to the client tat
within Server mayAsght pertrng
elase Stable for foxwOcrd and Suitable for scenarios where
înclede operatioms when you want to redirect
the dostinatiom is wittin Oclient to a different UR
the. web-applicakon when the URL
peaiall
outide of Current
web-applicaim
Oienk does not involve clienk Iovolves client browser
vlveret broser in_redirection in making request
DATE

Ri¿nt -Server Apotteeture

Client- Server Interaction


A Server in aContext of commputin qener
Lefers to a computer or sottware that poide
services, resoures(processin pQwer/ memoy), o oe
functinalities to other eomputers o cielti othe
netuk
avamole noct server, e serser,pai sef tabae
Zerrer
> HARDWARE SERVER :
.

AAphysical computer o aa dedicated device desiere


tonn server slw and provide Rervice to oha
devices through network.
Egi neb server, He server, mail Server,datahase Server

Software Server i
A coftnware applicatfon a progranm Hhat ru
aomputer and provides specific services to aliet.
Ea web-serrer sofware ke (Apache on
database senver sofhatare (pastqregq ysql)
Yurther ne can have multiple definitions of Server
as services, web server, applicakim server, server farm
datacentre
Multiplk webapplittons an he stored on the serve
oil be an Rdenifter(us
tOn erey application there will
Any sppYicatin acCessed by intenet s called a
w~b- applícations.
Whenever dient is request, it contains
URL tmethod
ethod typesending and data.
Ih req obieck,
get/post method bye, URL, and data can be queny Paramkrs
Response contains *s tatus code,tcontent type,*contt.
Content -type i TE is HTTP beader that îndicotes
bupe of dota contained in body of HTTP respmse.
speces 4he media hype of content heing
sent.
>status cade : Astatus eode is three oigit numeric
code retumed by Server to indicate out com!
of clients nequest maale throughwebbow ser
megest side URL 1
para meters
requst
*URL App URLS

method App"3
Data TApp2
respomse
Client network ntermet
Server

4 Statue Code
content type
contenb

Status codes are part of HTTP(HyperlextTransfer


Probocol) stanodards and are încluded io the
respnse nessOge header sent by the server.
Statuscode pxovide infornmation abauk suceest,
failre other comditicS related to rabuest.
HTTP Stateug codes re dinided into differentclasse
Rach vepresenting specifie categry respme
1XX, 2xx, 3XX, 4XX 5XX
DATE

-)1XX Informational):
These status code indicotes Hoat he
halreceived the clien! requast and igerver
e
Continuçng toprocess it and wil! provide
Cinal re spomse later.
2XX (Suce ss fel ) i
Theie tatl code indicateg thatclientk
equest suCceRrfutly received yndertood
and accepted
tedet 4Xx (ciient Erros) :
These stotus code indicates that client seente
to aave made an
issios ke requeit with malfunctBon or
unanthotjzed CccesS.
3XX (RedinerHonl):
These statue cade ndicatee that turther
actínisequied ta to complete the requegt
SXX (Server Error
These ctatsCode indé cates thot servet ha
Lencountered an erro while fulftling the reae
It's not cients foult and serve isisUresponsbe
Tesolving Hhe ss ue

Commony encountered HTTP tatus codos e


404 (No found): Reqested nesource is not fourd
Server
S0o(Interna Server Eror) A error nessage
generie
indicating server ha enountened an eror
unexpeced comditon,
DATE

Actual Content i Tt refers to mneaníngtu infor


mation on datta within a do cumen r a
ale. webpage or any ather fox m o Communicatin
what is ServletContext
Servletlontext ia an interface that repeients
Cammunication channel hetween Servlet and
the Servlet caYmtainer, Tt provides intormation
about web-application1 environment and serves a
centcad repost kery fo sharing cornfiqurati on
informaticn, resolrces and contmunicatin amonq
Sernlet in same weh-appliatien

Servlet 1 Servlet 2

Serylet 3
D8Canti
SeryletContext
web-apptcatior
In web-app Servlet lemtext i an object
e) what kind of Object P
Serrlet Conke xt kind of obËeck.
#What is Serylet Context object ? who is respcnsible "
Tt is an object in web-app and web- ton tainer wil
Cne ate ServletContlext object. Asaproggomnar, no nedl taomy
Ho to Store alue in SerletCntext
whenerer were otoing songething in ServtetConkexk
DbËect, wehe going to ore îtit in keyyale pair
These key- vale pair wU be stored în wwehxm
'DATE

<context -param>
<param-name> key <param-name>
<param-vaue value slparem -value
<lcontent - param>
We can have multiple <Contet patam>
When does ServletContext obieck is qing to be ceat
we
dapla web-opplicationit is cedb
Annotaion
DATE

Java Serlet onfig is interfaca waich i


pnesent in Tava Serulek API,Hhet provida Serlet with
allows a o Serulet
inatantiation
to accesS Configurakion
parameters.Tt
infoxmation specified
Web.xmd dutng it's inatantiatieg.
Cinsidoring web-app uith muld iple serulets
Suppose nead to Lane SONe informatieg
which neede to he stored particuloar
Seryletin such Case we make

Senvlet Config
Servlet A.
Servlet Conial
Serrlet B
Servletonis
Serslekc O
Servetonfia
web-app it One fox Serslet
a
object
Servlet ConfigÞ obierk of Serylet A a not visible to
Serslet Configandbieck
Servlet C
ServlekB
Serslet Config obiect of Serlet R not

rsible ServleA and Serylel C. ec


Similarly A not issble to 8
Caeates Servlet Config abiccts. These
Web- contanerQvailable to elar
obfects that parlice
Serlet
weh-container Coreates
fnctantiate. Serylet clase.
DATE

How to Store and netrieve values rom


the anfig ohËect
<web-app
< servlet>
< Servlel -name Pageh </servlet -nam
<servtet-classedu, ty. PageA </servlet-da
<init- pram
Kparam-nam? key </para m
-nams
param-value> volue </param-valu.
<linit-param>
</servlets
<servlet- appin >
<servlet -names PoqeA <Iservlet - name
<url- pat tern page- a <lurl- pattern)
<servlet- mapping
<serelet -mapping
<servlet-name) Pageß
PaqaR </serylek name
Surl- patbrn> /pase-be lul-paHern
<servlek- mapping
#Annotoation boded Confiquation i
OwebSerylet Cur lpatterns = "IMySerylet"4
lpatterns=
onAnnetai
fnitfara ms =
WehInitfarom (nome:"para mName Yalue e

publie class My Serslet entendls HTTPSeret


servlet ode
DATE

Que what if both annotation baled e web.xm hased


Confiquraions are provided 2
Owhenuing both configucrationi fo
Seeulet , 4he etting pxeddd Qweb'erlet
annotalion take pre edence. coneipondi
sttings pxoxided webml file dig
Sessin Management i
Sessicn Managtment is cucial aspect"cbodaveloponakt
that allowr Server to maintain Stateful ntom
about User acmes multiple Requests.In Tav
Java
Serxleb,Sesslan used to stone
ypicaly
User's specific data 'Such a user preferences
items Quthenticationdetails
shepping cart

A sessfon to track wser's interactian


mith website coORS multiple nequett Tt
allaws Seryer to stase wer-specific fnformahom
and as8ociate wwith uniquesession d.

Sessim

Step I Creationi
A sessicrn neate he Ainst time when
usen -accessee the webite

The used to associate ub


Saquant requeit ith Sesgion

tep Session
Session
Timeout ?
Lhave timeout ! wer s ina ctive for
Speified duration
Juration the session expires,
Task &
there in 'DATE
Houw many
mamt
Sessiom.
g
Tava
ree

Servlet . tracking
lessioo Tracking
There are multie way by lich we
track Seseion, an

) Coogkie e CDefault mechanim)


The cends
Servercends unlgut session id tnn a Cooki.
stored on clients side.

2) URL Rewibing
Sessionid e appended to URL
gerver Rt treated as
hence Server member who the cient i
in the next request. Tais is Lstate lesr bokeyio
Soagain client necds to itroduce to serve
erery requsst to Kerver.
To avoid this we ne adko take helo of sesto
by which state ful behaviaur can be achieved.
(S&rrer will ecognize client hcough mutife
egests)
4What are Coogkie
Cooakie are Smal piece of data stoed on
user's cients device web-bro3seL

Thay are Careaked


mebsite and
when
deigned to hald
teot
modest
a

CmauntE o datasoeific to a a prtieular


client andwebeite.
DATE

Purpore o coockies 9
D>seselon Management
Coonkies hetp iinn f o r k e r sensing, They
stoe Sessio
stay lu4ged in as allowing
theywebsit
nacigat though
users to

2) > ditferent pages


pages af
ercmalization1
Coogkies olten used to emenber
pre ferences and gettingspraviding personlized
brnwsing experience Tht incudes langage
3)>
prefereces, theme choices, etc.
Trackingand
Webste Ownersse analgtie 2cooakie to collect
data
time
User behaviour such as page vievs,
Spent site and most viewedootent
This inforrmatfon valuabsle for analytis
and împroin webeite
4)
4 >

Cooqkies play crucial rale in wser -authenticak


Coáckie store information that allowS a
ter to emaìn autthorizedo they don '4
have to login erenytime partilula
weh-apalicalfoq.
s) Shopping cart Manaqemant
In ercmerce weheites, coockies sed
to stone
that
items
cart
sens
CeetaiAg tents shapping
art Cart.ensuhgÞ
persictent
User navigate thaoughout
)
Tagetcd Advertiing
Avrertisec doobkie to track wser interest.
and display tangctedandadi, his depend on ers
broysin hist behaviour.
'DATE

A Cookie in Java o
Tavax. Serylet.bttp. Cooekie.
olo3t is preJent

Initkally Caokie
Cookie
is Created in
Serstored
ver hyom -
Server, the hat wil be
sponse and sent to the client.
he
client will take
The hose Cookies ond
store it inbrowser.
When client makes another reguest, client
uillsend
iqutst along
Lnq with.
with cookie,
NOTE & Tn cOOkie we shore daba in kayyvalut.gi
We n CTeate Cookie object with help of
Comstaucton, in Caokie class wehavé to
Comstactcons
) Cookie ) f

2 Coskie (stíng keq, hing valuc)


After creatirg cookie , Ne
ceating an at ach te it to
espome The brewser wil ead nepone
in which helaave coo kie andtone
þrowser (nhich
next
isclient-side
com se cutive
bnouser wil Qend requst along witth caakie
regt cookie object
brower
Cookie req 1 Coskie
Conshuct Cookie objt) Object
Tesp fcodkieobeet
Serrer

You might also like