0% found this document useful (0 votes)
28 views24 pages

EJ Unit2

Uploaded by

Towhid K
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)
28 views24 pages

EJ Unit2

Uploaded by

Towhid K
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/ 24

Request Dispatcher

UNIT - II
I ~ • I~

I

• I

REQUEST
~
I DISPATCHER

t
j7.1 Resquestdispatcher Interface e. RequestDi spa tch er
erf ace is def ined in javax.servlet packag
RequestD isp atc her int co11:po:1ent . Th e
ues t of clie nt and tra nsf er control to anot_her we b 1s use d as
object contains req cre ati ng obj ect of RequestD1spatcher wh ich
pon sib le for a par tic ula r
servlet container is res loc ate d at a par tic ula r pa th or giv en by
ver res ou rce of a
a \-\rrapper aro un d a ser
to the com po nen t yo u can inv ok e the for wa rd me tho d
l
name. For transferring contro is int end ed to wr ap servlets, bu
t a ser vle t con tai ner can
pa tch er. Th is int erf ace
RequestDis rce.
ects to wr ap any typ e of resou
create RequestDispatcher obj Pro gra mm er.
ica tio n bet we en the Ser vle ts is an im po rta nt tas k to the
Commun
patcher
7.1.1 Obtaining an Objec
t Implementing RequestDis an d
ect , tw o sty les exi st - ~si ng Se rvl etR equ est . object
For obtaining the obj tho d ret urn s an object
get Re qu est Dispatcher(String path) me
ServletConte xt obj ect . Th e rvl etReq ue st and
her an d the sam e me tho d exist in bo th interfaces of Se
of RequestDispatc
ved like following :
ServletContext. This can be chi String path)
ntext.getRequestDispatcher(
• javax.servlet.ServletCo String path)
quest.getRequestDispatcher(
• javax.servlet.ServletRe Re tur ns a
get Re qu est Dis pa tch er(String · path)
RequestDispatcher loc ate d at the giv en

atc her obj ect tha t act s as a wr ap pe r for the res ou rce res ou rce or
RequestDisp be use d to for wa rd a req ue st to the
isp atc her obj ect can
pat h. A RequestD dy na mi c or static.
lud e the res our ce in a res ponse. The res ou rce can be
to inc Th is me tho d tak es the
er get Na me dD isp atc he r(S tri ng na me ) :
Request Dis pa tch dec lar ed Yia

vle t (an d JSP pa ge s als o) as pa ram ete r wh ich is
nam e of the Ser t/J SP
exp ect s log ica l na me of the de sti na tio n ser vle
Deployment descriptor. It
pro gra m as arg um ent value.
ESTDISP ATCHER
[7.2 METHODS OF REQU
tw o cases :
RequestDispatcher is use d in nt l.,.ets
nse (ou tpu t) of on e Se rvl et int o an oth er (th at is, clie c, '
1.. To inc lud e the res poServlets). .
the res po nse of both
ent calls a
rvl et to ho no ur (th at is, cli
2
· J 0
f~ ~a rd the cli
erv et ut response to client
ent req ue st to an oth er Se
is giv en by an oth er Servlet)
.
, /IW<' (T, y,}3,Sc.-f.T.) (Sem.~1,,)
Ettterpriee
_.,,.,,. l ( ) and RequestDispatchl.!t
62 ~· Ji tchcr inc1u<. e
.. . thods exist : J{cque6ltl spa
There art' two me ·
forward( ). l d
2 1 I dude ( ) , ,, onse respot1se) m~thod inc u es thl!
7. . n ServldReq,iest req1w1t, servlt1Resp th 's melh()d enables prograromatk
The inr.ludt'(, ' . he response. In essence, .' h e lements and parameterli
content. of ~ resoun'\~n, ~rvletResponse object has its 1pat annot change the respon~
server-side includes. e r The included serv et c
remain unchanged from the ca11er s. o make a change is ignored.
status code or set headers; any attempt t be either the same objects as were passed
The request and response parametersbmu~bclasses of the ServletRequestWrapper or
, · e method or e 8
to the calling servlet s serv1c wra the.en.
ServletResponseWrapper classes th8 t p
7.2.2 forward ( ) 1 ·t Res onse response) method forwards a
The forward(ServletRequest reque:, s~inentrservlet/JSP file/HTML file) on the
request from a servlet to anoth~ wfet ~~~o preliminary processing of a request and
server. This qiethod allows one erv
th urce to generate the response. .
ano er reso d hould be called before the response has been committed to
The forward() meth\ ~ output has been flushed). If the response already has been [1 ~
the cli~td(bethifo~e resepthoon~e t:rcfws an IllegalStateException. Uncommitted output in the C
comnu.tte , s m f d view :
response buffer is automatically cleared before the orwar . .
The request and response parameters must be either the same obJects as were passed you a
to the calling servlet's service method or be subclasses of the ServletRequestWrapper or i.nforl'.
(
ServletResponseWrapperclasses that wrap them.
7.2.3 Differen~e between forward( ) vs include( ) method addr
To understand the difference between these two methods, let's take an example: you
Suppose you have two pages·x and Y. In page X you have an include tag, this means that inf01
the control will be in the page X till it encounters include tag, after that the control will be
transferred to page Y. At the end ofthe processing of page Y, the control will return back cool
to the page X starting just after the include tag and remain in X till the end.
In this case the final response to the client will be send by page X. wel
Now, we are taking the same example with forward. We have same pages X and Y. In a f
page X, we have forward fag. In this case the control will be in page X till it encounters pa,
forward, after this the control will be transferred to page Y. The main difference here is tin
that the control will not return back to X, it will be in page Y till the end of it. se1
In this case the final response to the client will be send by page y. se
s~
/~-3 Re:uestdisp~tch~r Application \
S1
thN1·sobte ·k~hethapphca~10nl de~onstrating use of RequestDispatcher interface is covered in t]
oo m e practica section.
(

1.
QUESTIONS }
What is RequestDispatcher interface? How to obt . Ob' .
E I · h · am Ject 1mple1nenting it?
2. xp am met 9ds of RequestDispatcher interface. .
3. What is difference between difference betw f
. een orward() vs include() method?
[fm)1!JI] 00!1iil; :
~~~ ,,.,,..,.
cookies
CHAPTER
eludes tl)_
am-.--...
---....q c\t' ~ UNIT - II
ara:rnet l~
el'
respoh s
~1s~
• • •
re Pass
rapper eq
O:t
COOKIE S

♦ C t •
·ttect to
has been
tin the ~.1 Introduction
Cookies are very small text files placed on your computer by a web server when you
view some sites online (not all web sites place cookies). They're used to store data ab01.~t
e passed you and your preferences so that a web se~er doesn't have to repeatedly request this
pper or
information, potentially slowing down load time.
Cookies are commonly used to store personal registration data like your name, your
address, the contents of a shopping cart, your preferred layout for a web page, what map
xample: you might be looking at, and so on. Cookies make it easy for ~eb ~~1:ers to per~onalize
1
?ans that information to fit your specific needs and preferences when you re v1s1t1ng a web site.
f1 will be Cookies may also be called a web cookie, Internet cookie, browser cookie or HTTP
n back cookie.
The main purpose of a cookie is to identify users and possibly prepare customized
w~b pages for them. When you enter a website using cookies, you may be asked to fill out
a form providing such information as your name and interests. This information is
ounters packaged into a cookie and sent to your browser which stores it for later use. The next
her e is time you go to the same website, your browser will send the cookie to the server. The
server can use this information to present you with custom pages. For example, instead of
seeing a generic welcome page you might see a page that welcomes you by name or
shows when you last visited the site.
A CQOkie will typically contain a string of text with information about the browser.
So_me websites do us~ cookies t? store more personal information about you, however,
ered in this can be done only if you provide that personal information.


.
Cookies have parameters that can be passed to them :
The name & the value of the cookie.
• The ~xpir~tio? date of the cookie : This determines how long the cookie will
remain active m your browser.
• . is valid for : Web pages outside of that path cannot use the
The path the cookie
cookie.
• The domain the cookie is valid for : This makes the cookie accessibl t O
any of the servers in a domain. · · e pages on

[:lJi)1(f] lll!JU1j l3
~~~
. rr· YB.S<".-/.l. ~ •111 -~v)
E,1tapn$CI fat'/1 1 • • • Cookies
f;/'t/'ft' . ookie cAfl only be used_
S.3 W
64 . . Th·._ indic.1lt'S that the c
• The need for a secure connection. l , C
under a secure server condition. different ?a
be u sed fot t(~
()\\
8.2 Kinds of Cookies • tor~
n,ere are three \\'P\! of Cookies:
· . kic 1 ttac.hcs itse lf to • to\l~c
8.2.1 Session/Transient Cooktes"t porary cook',e,'' , this type of coo . ' use
mainly . •d by on\'1ne e-co~

user's computer when they c~ter :~n ,:r


These are also knm\'n •1 5 a c~ b wsc a website. 111csc •~re

shops and allow us to k~P iternd A ~ession cookie does not co


line These cookies
basket when shopp1n1f:;info.r rnation from a



lo itntit
to anal
in the
. w.hen
e,p1re doseit .sits on the system,
. 't .iswhile
, the browser they belong to the
sts with the • to?er
user's computer or act1v1) r can be difficult be(aUS~ .
Disabling session cookies in your browse) all administrative ab1hty re beof pa
. ·r and sut,sequent y • to build
website the user is v1s1 ~g
Secure we
administrators of the website.
C }des ·t · page; without
., ., ., rennanent/Persistent 00 . d t disappear after a user eXl s a site.
o..-. · tent cookie oes no tinuing t product added
unlike session eookies, a persIS . . . ation date with the cookie co_n .o
n,ese types of cookies have ~ ~pecif1c exp~ time a user visits the site until the expiry • CustOtnet
tranSIIlit information to a website s server eve • Persistent
date comes up. . al kn s ,, tracking cookies" as marketers • Wish
• persistent cookies are so own a .
For this_ reason, . bt . d from the cookies to study user behaviour over a certain • Produc;
can use the information o a.me .
• Custom
period of· time. ki also used to keep users logged into certain web s1·te, thus
PerstStent coo es are ·a1 h tim th ant t • Retainiti
eliminating the need for them to enter their log in credenti s eac e ey w o Where are Coo ·
access the site. Cookies are t:iai:
,..From a security perspective, it's important to note that users should ~ot enable the
vary depending on
"keep me logged in" function offered on websites. This is not a safe J?ractice and can be . listed below :
dangerous if any unwanted third-party were to gain access to your device.
Some websites allows user to disable their cookies, this causes problems in the • item, and fr
functionality of the website or browser as information needed to run the sites such as user Files' buttor
IDs and recently saved searches will not be available if the user has disabled the cookies Cookies ha~
that retrieve this information. In lieu of disabling cookies altogether, a safer option might you which
be to clear your cache ,af cookies every once and a while to free up space on your device
Note: the
and get rid of any unwanted cookies. Explorers
8.23 Third Party Cookies
Normally, a cookie's domain attribute will match the domain that is shown in the • Microsoft

web browser's address bar._ ~s is called a first-party cookie. A third-party cookie, • Firefox?.
howeve_r, belongs to a domain different from the one shown in the address bar. This sort Firefox b
of cookie typically appears when web pages feature content from external websites such link, an
~ banner a~vertisements. This opens up the potential for tracking the user's bro~ sing selected
history and ts often used by advertisers in an effort to serve,relevant advertisements to
all, orj
each user.
onyo,J
As an example, suppose a user visits www.example org This web ·t ·
advertisement from ad.foxytracking com which h . d . . s1 e contams ah • Googl,
belonging to the advertisement's dom:ain ('ad f t , kw en) ownloaded, sets a cookie 'Custon!
b . . ox rac .com Then the user . .t h
we site, www.foo.com, which also contains an adverti . f , v1s1 s anot er screen
and sets a cookie belonging to that domain (ad f t ~ment rom ad.foxytracking.corn then d
cookies will be sent to the advertiser when load·. o:;a.c -~om)._ Eventually, both of these be sh
website. The advertiser can then use these coo:e~ toe~u~l;:tisements _and ~isiting their
.
user across all the websites that have ads from th'1s a d vertiser. p a browsmg history of the

-
~ [:ai)¥f]

~~~
lll!Jirtj l3
65
Cookies
8.3 Where Cookies are used? . · · te
. and track users as they nav1ga
Cookies can be used by web servers to identity . t 0 a website. The cookies can
different pages on a website, and to identify users returning
be used for following purposes :
• · ·t the website.
• to recogruse your computer when you v1s1 . d to enable the use o any
f
• to track you as you navigate the website, an
e-commerce facilities.
• to improve the website's usability.
\

• to analyse the use of the website.


• in the administration of the website. hi h
the • to personalise the website for you, .including targeting advertisements w c may
the
be of particular interest to you.
• to build a profile of your web surfing.
Secure websites use cookies to validate a user's identity as they browse from page to
Site. . . . . d h be tered between before every
page; without cookies, logm credentials woul ave to en
~ to product added to cart or wish list. Cookies enable and improve :

Iiry •

·Customer log-in
Persistent shopping carts
rters
tain • Wish)ists
• Product recommendations
hus • Custom user interfaces (i.e. "Welcome back, Steve")
t to • Retaining customer address and payment information (only up to permitted.)
Where are Cookies Placed?
the Cookies are maintained by your web browser, so the method for viewing them will
be . vary depending on which browser you are using. The method for how to view cookies is
listed below :
the • Microsoft Internet Explorer 8.0-11.0: Select the 'Tools->lnternet Options' menu
item, and then click the 'Settings' button under the 'General' tab. Click the 'View
~~=:
~ght
Files' button to see a list of the temporary internet files that Explorer h as stored.
Cookies have names that begin 'cookie:' - the Internet Address column will tell
you which website created the cookie. ·
ice .
Note: the 'Tools' option can also be accessed by clicking the 'gear ' icon in Internet
Explorer's toolbar.
• Microsoft Edge_: ·Mic!osoft Edge does not appear to •provide an option to view
the individual cookies. You can delete all cookies, or enable/ disable them.
kie,
• Firefox 7.0 and newe~: Select the '!ools->Options' menu item (ma be und
sort Firefox button) and chck on the 'Pnvacy' tab. Click the 'rem . d ' Y_d al er ~he
•uch . . will b h li . ove m 1v1 u cookies'
link, and you · f
es own a st of all cookies stored b Y p ire
~iJlg ·h ox. You can delete
selected cookies if you w1s , or you can click 'Remove Ali C k. ,
to all or simply browse through the list to see which w b . ooh ies to delete them
e sites ave store d cook 1es'
r
'
on your computer.
a!l • Google Chrome : Choose 'Settings' on the , arall 1 b ,
~kie 'Customize and control' menu), and click the 'Adv p d~l' ars button (or the
~her screen In the 'Privacy and Security' section cli'ck anche , ink at the bottom of the
· · ' on t e Co t t ·
ro111 then click the 'Cookies' option, followed by 'See all ki n en _settings ... ' button
,ese be shown a list of all websites which have store~o es _and site data'. You will
. cookies on your computer.
i,eir
the
f 1/flr"frr--- - - - - - -
·/' y ,t1.Ut . I I l tF,n11. v
( th 1
Ft//l!Y/IY/81' /1,Url I ,
~ . •I rtlrtp, fl i .,,,J,11-c' sl,,,.,,\
,,..,..,. Ides, and ,,c 11 ,
66 otl to sec the coo f
Selecting a website all_ow 6 'I , ,. 'H,Hl' ,nr•tt'' (Wl11tl1"''~J
you
the data stored in it.
'P fcrcnces,..
'on the '6eltJnW' " I ·111 Ir thi lfJf'lt,11~ '
, cy' tub ,1nt 'r1 yotu' 'o111p1111.,,
fl, v~t
-'ar1·. Choose re peJ1 the 'l'l'JVU I 1 /uil Uii
!'st of all cook1er:. r:, l ·Jl +i11}' i r1r,1110·✓1 ,,, 11,ti /
App 1e 5 cU • QS) then o , •tn r•r•r ' ,
( ',, ,j; /(- ti 11 ,, ,t-
• th Safari menu (Mac '
or e ·11 be i;hown a I • lhcrn c.111c c. c: ,
button. You w1 b deleted by 1:1elcd1ng rI '•}'' ,, 1~
1
ndJ1 1
e
. 'dua1 co okies can1' k'ng
Jnd1v1 'Remove All' · j-"I I"' IJlfl tJt)
can all be deleted by c ic l ( '( 1 ,1, 1' ftilU'- j
8.4 Creating Cookies usi~ servlel lei hltP• Cookie which ~cs wo ,YI ny, wii I, "" ,f"
1
111 1/
(r,,1Tf'
t: J 1•
t
1~ ,1 l,lt U1
14
Servlet API provides Javax.sen' . 'I /ht t I(.' / f! I I ; }!i
t l ,c ti writ 11 1:it }n, "
very easy. jJI :,tJ' f/ 1,
I' $$1, 'I
8.4.1 Working with Cookies
C kie Constructor 11 '
ount of inf<Jnr1;1IJ'1/I U:!11\ ~vst '
HS , J'i,,1dl11v, ( t,•,~
I. Creating a oo kie Cookie() constructor is used, a a;~ t::Sent bad(' to th1• r,crv1 ' · A (, 111 I fl1, J#,1d
To creates a~\ browser, saved by the browser,~ a rnonly Utwc.l h,r' fWHf-iHm
by a servlet to a e . .d tify a client, 60 cookies are corn · c;,,,,.v id I
cookie's value can unique1y 1 en 11
'b t such ' 11:J ti ~omrr ,nt, p,ilh No*"' : thr 'I/ •I
anagement '/

m A k'~ has a name, a single value, and optio~al attn bu esSome


coo 1 . and a version num er•
Web
broWHf'r~, h,J'1,,
h
1 lui/1 /' 11 , ,

and domain qualifiers, a maximum age, . them sparingly to irnl)rnv1· l tJ 1Jnf1,rl11r,,it,,; \/


bugs in how they handle the optional attributes, so use find H,,,1 ',,,,'I. ri
by uHi nv ,1r1 , ...1 :,rtq,k ~
interoperability of your servlets. k' to· the browser lh1•
The . servlet sends . c~o ies
HttpServletResponse.addCookie(Javax.servlet.http.
Cookie) method, which udd~ fi1•kll,
ta time The bmwm•r ic;
1,

C(.1(: id t·
hbHIY,
l
f
to HTTP response headers tok_sen; cook~s~~~h:e:::;;~O : : : ies totul: trnd mi1y 1lr11lt f(H(< r,r
expected to support 20 coo 1es or eac ,
H(",1
cookie size to 4 KB each.
Syntax: public Cookie(java.lang.String name, java.lang.String value) !) 4
1t constructs a cookie with a specified name and value.
Some important methods of Cookie class are :
1. getO.>mment(): Returns the comment describing the purpose of thif; coo.Ide, ui,,cd
at client side.
2. getDomain() : Returns the domain name for the cookie. We use 1:1elDomain() 'l 'h j,; l•i.'.
method to set the domain name for cookie, if domain name is set then the cooJt'.iP c·,,oVi•·\ \ ,;rt
will be sent only to that particular domain requests. If jl>IJ T
3. getMaxAge(): Returns the maximum age,in seconds. We can use setMaxAgc() to ,HHl put Hw
set the expiration time of cookie. in•,1,inc:c tJ 1,
4. getName(): Returns the name of the cookie, can be used at both browser and Ma
server side. There is no setter for name, we can set name once throu gh comitruclor
only.
5· getP~th() : Returns the path on the server to which the brow ser rclurns this
nl WWe will see 1't' s exampIe w h ere t h e cook'1e w1·11 b e sent to specific rcsourre
cookie. for
~es~· e can use setPath( ) to instruct browser to send cookie to a patlkular
urce only.
6. getSecure(
protocol ) £~. Retu . the browser is sending cookies only over a 1wcure
. ms true 1£
setSec~e~r) se if the browser can send cookies using any protocol . Wc can uHc
Afh-
protocol. th
me od to instruct browser to send cookie only over secured
lhc <<H,ki
7. getValue( ) : retu .
method to changer;: the value of the cookie as String. There is also setValue( )
e value of cookie.

[:m)1(f] lll!JU1; l3
~~~
67

) : Rctums the versifm of the protocol this cookie complies . 1.-..


H, Pl!,,tVt•r9ton( I l • , Wttu..
rh,'l'l' 111 n sn a Sl'llf'l' t1)l'l H)ll1 llll' , l'T'SI()\)
'). i~llttpOnly(): ~ 'lwd,.s 1 wlwtlwr this CoPkh.• • h,,s bel'n
. marked as HttpOnlv.
.1 Th ere
is .,tsn n St'lll'r nwt lll'lu l 1Mt,~ l ' c.ln USl' lo instruct c11cnt to use it for HTTP only.
S('ttln~ .,nd s~ndlng .1 Cookk
11. \ l, crin writ,' Cl)l)\...it-s u:-<ing t lw H lt pServlct Rcspon~c object lik(! this :
11
L\)l)kit' ~·tH,k.il' 1ww (\1t1k.it'("t11)'Cook,c", "myC0okicValuc");

n•splmst' ., 1d t l C<,t' k. it•(Ct)l) kit•);


A:.
, •tHI l,.,n
Sl'l', tlw cot'lk.il' is identified by a name, "myCookie", and has a value,
"im ~\)t)kil•\ ,1lue" .. Thus, you can l1dd many different cooki~s with different identifies
•t•~) lt '~ ,1 bit hk.t• ,1 l lnshtl1blc.
( thll l WlwtH.
• • • •
ncccsses the web application it submits the cookies stored on
' Vl't' the bl'owscr
tht' di1..'nt nh1chhw to the web application. Only cookies stored by the accessed web
,ipplicatinn ,11'1..' submitted. Cookies from. other web applications are not submitted.
Ill. Reading Cookies Sent From the Browser
'r. NI cnn rt'Ud the cookies via the HttpServletRequest like this :
Cookie[ l cookies = request.getCookies( );
Path
have Note : the gctCookies() method may return null!
the Now you can iterate through the array of cookies and find the cookies you need.
Unfortunately there is no way to obtain a cookie with a specific name. The only way to
find that cookie again is to iterate the Cookie[] array and check each cookie name. Here is
the
elds an example:
er is Cookie[] cookies = request.getCookies( );
itnit String userld.= null;
for(Cookie cookie: cookies){
if("uid" .equals(cookie.getN ame( ))){
userld = cookie.getValue( );

11
This example finds the cookie with the name 11 uid and stores its value in
Cookie[] array.
If you need to access more than one cookie, you could iterate the Cookie[ ] array once,
) to and put the Cookie instances into a Map, using the cookie name as key, and the Cookie
instance as value. Here is how that could look :
!Id Map cookieMap = new HashMap( );
tor
Cookie[] cookies = request.getCookies( );
}liS
tee for(Cookie cookie: cookies){
Jat cookieMap.put(cookie.getName( ), cookie);

re
ge After this code is executed you can now access the cookies in the cookieMap using
ed the cooki. e names as keys (cookieMap.get("cookieName")).
'
Enterprise Java (T.Y.B.Sc.-I.T.) (Seni.,~

68
IV. Cookie Expiration . . the cookie expiration time. This time tells th
One important Cookie setting is . it should keep the cookie before deleting it. ~
kie hoW long tune
browser receiving the coo . . .a the setMaxAge( ) method. This method tak""
. anon tune v1 1 -~
You set the cookie expir . . t live as parameter. Here is an examp e:
d the cookie is o . .
the number of secon. s w Cookie . (" u1"d" , "123")·,
Cookie cookie = ne
. (Z * 60 * 60); // 24 hours.
cookie.setMaxAge 4
response.addCookie(cookie);.
11 11
;.,.,stance with the name 11 uid and the value 12311
Cookie .... hours using the setMaxAge( ) method·
. ti.aon to .24
. examp1e fir st creates
This
Second, _1.t sets the expira minutes x .24 hours (24 x 60 x 60). Finally the example sets the.
60
nds lx tResponse
24 h~urs 1s 60 secoSe object, so th~ cookie is included in the response sent to
cookie on the Http rv e
the browser. ~
v. Removing Cookies ~ - 1
. may want to remove a cookie from the browser. You do so by setting

~
Sometimes you th . . . t 0 1 If t th
the cookie expiration time. You can set e ex;rrratio~ trme o or - . you se e
. ti· ti·me to o the cookie will be removed immediately from the browser. If you set
expira on d h h b h . d
the expiration time to -1 the cookie will be delete w en t e rowser s uts own.
eV~
Here is an example : that has
11
Cookie cookie= new Cookie("uid", ");
B1
cookie.setMaxAge(O); requesji
response.add Cookie(cookie); sendin
sendin
I£ the browser already has a cookie stored with the name uid
11 11
, it will be del~ted after
T
11
receiving the cool<ie with the same name (11
uid ) with an expiration time of 0. If the multi{11
browser did not already have the cookie stored, this new cookie is just thrown out both a
immediately since its expiration time is 0. about
respoj
J
~:~
QUESTIONS
1. What are Cookies? Explain its parameters.
2. Write short note on types of Cookies.
3. Explain the uses of Cookies. mai~
4. Where are Cookies placed in computer? partil
~
5. Explain in brief the creation of Cookie.
6. List and Explain important methods of Cookies class.
7. Explain setting, sending and reading of Cookie in java servlet.
8. Write short note on Cookie expiration and removal.

l":0011(11 lll!JU1.; l3
~~~
I'> f •
'I 111
69

r·~;:.-~~~·~:~;~~~~~ l
,--• ♦ ♦ • \

I1 SESSION \

~
t _ _ __ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ ___J
r;;-; Wh.1l Ar-;Sessions?
rrrr protocol and Web Servers are stateless, what it means is that for web server
•vNY1 rrquest is a new request to process and they can't identify if it's coming from client
~h.>I has been sending request previously.
But sometimes in web applications, we should knowwho the client is and process the
request accordingly . For example, a shopping cart application should know who is
c;cnding the request to add an item and in which cart the item has to be added or who is
sending checkout request so that it can charge the amount to correct client.
The Session is a conversional state between client and server and it can consists of
~ed after
multiple request and response between client and server. Since HTTP and Web Server
· If the
both are stateless, the only way to maintain a session is when some unique information
wn out
about the session (session id) is passed between server and client in every request and
response.
A session is a group of user interactions with your website that take place within a
given time frame. For example a single session can contain multiple page views, events,
social interactions, and ecommerce transactions.
The Session simply means a particular interval of time. Session Tracking is a way to
maintain state (data) of a user. We need to maintain the state of a user to recognize to
particular user.
Session comes in two types :
J. Statefull session : It creates a channel between client and server, session will be
dosed if any one of the end get disturbed. And they need to
re-authentica~e again to continue their process. Example: SSH, FTP, Telnet etc
2. Stateless session : Once the user is authenticated it maintains a token to do the
further process, so there is no need to maintain any channel between client and
server, the client needs to re-authenticate if the token is lost or expired. Example:
http protocol, all web based application. · 5t
There are several ways through which we can provide unique identifier in reque
and response.
3• User Authentication : With ·this approach user can provide authentication
credentials from the login page and then we can pass the authentication

l:oo»mlH!Ju§@
l«]~~
- r1
y.a.sc.-l.T.) (Sem.-v) 5e~s10 e"er' the sa

ti"
Enterprise Java
h session-
.
([
.
This is not ve~
d . fr
iO·
.,efl
r10; tl'le use~ \c
te a sess1on
tl"f1' d client to rnaintain t e user is logge in o~ ev 1·p_~
70 een server an k if the sarne tetl'.!'- 1,Jf ecycle of l
·nforrnation betw ·t won't wor
1 ffective method because 1 field in the 1-ffML ¾cl 9J.·3 1'-1ost servlet 'c
~ifferent browsers. create a unique ~dde~o the user and keer tra~k_ 'the user ~
aTML 1:Iidden Field : We can set its value unique se it needs the o~ to 1.- 'the servl '
4. user starts navigating, we ,can used with 1inl<s becau erver with the h1ddel\ 2.
when . n This method can t ~e de frotn client to s f ld value from the 'the servl
of th~ sess10 . t' e request is rna t the hidden ie 3.
. The serv
be submitted every un b cause we can ge 4:-
field. Also it's not sec~e h:ck the session- .. ararneter with every Let's sa')
HTML source and use it to d session identif~er p t dious because We 5-
an appen a . This 1s very e ·t' "fhe use
URL Re-writing : We c k of the session- d r:nake sure 1 s not 6-
cookie '
5. request and·responseftohi~eepp ::neter in every response an
t 5 Since tl
need to keep track o .arneters. . sent by web server 11\ •
1-
clashing with other par 11 piece of inforrnation t~at Wh1sen client rnake further So ser'
.es are srna r cookies. tr 8- 11
6 Cookies : Cook 1 t stored in the browse utilize it to keep ack 1-li, T'
. h der and ge s h der and we can . bl h
response_ ea cookie to the request e~ . but if the client d1sa es t e TheU
request, it adds the . tain a session with cookies 9-

then itWe
of the. session. wont rnain
cc;11work. A.Pl 1·s built on top of above 10. Aftel
cook1es, . Management d _ _ ses~io
7. Session Manag~ment A~I : ~~:::f the rnajor drawback of these rnetho s are: 91 4
methods for session tracking. k the session, we have to store session
d 't want to only trac ·11 .
Most of the tirne we on . future requests. This w1 require • Sess
• rne data into the session that we can _use in .
• Info
asolot of effort 1·f we trY to implement this. . 1 all of thern won't work
• All the above met o s ar
.
h d e not complete m themse ves,
articular scenario. So we nee a sou i
d 1 t' on that can utilize these methods
.
• Ses
tha
map . "d session management in all cases.
of session tracking .to provi e
Management API and J2EE Servlet technology comes • Ea
That's why we need Sess1on • J 0
with session management API that we can use.
9.1.1 How an H'ITP session expires? _ _
• i~
By default every web server will have a configuration set for expiry of sess10n objects.
Generally it will be some X seconds of inactivity. That 1s when the user has not sent ~ny • 1
request to the server for the past X seconds then t~e sessi~n wi~ expire. When a session
expires, the HttpSession object and all the data 1t contains will be removed fro';' the
system. When the user sends a request after the session has expired, server will treat 1t as a \9.2 Se~
new user and create a new session. Se)
Apart from that automatic expiry, it can also be invalidated by the user explicitly .
HttpSession provides a method invalidate( ) this unbinds the object that is bound to it. reques~
some
Mostly this is used a't logout. Or the application can have an absurd logic like after the
conve
user logins he can use the application for only 30 minutes. Then he will be forced out. In
such scenario you can use getCreationTime( ).
T
descr
9.1.2 What is Session ID? and
A session ID is a unique number that a Web site's server assigns a specific user for the
duration of that user's visit (session). The session ID can be stored as a cookie, form field,
or URL. Some Web servers generate session IDs by simply incrementing static numbers.
However, most servers use algorithms that involve more complex methods, such as
factoring in the date and time of the visit along with other variables defined by the server
administrator.
co
_ ~very time an Internet user vi~its a spe~~i~ Web si~e, a new session ID is assigned.
f:tiimr Rf;fnd
-
~

~~~
then reoperung and v1s1ting the site again generates a new SeSS\(111
..;,_,,,.,;,,,,
O tJ
l ,en
tl
,.ovvever, ,e same
· l·f the user. eaves
l h
.
session
.
.ID 1s sometimes mamtamed
. .
-- ......
as l
d t .e site in question an d returns I ong as the browse •
7
1
e, . ,ate a session an assign a new session ID afte f . _n some cases W r is open,
ier1t1Ll r a ew minutes f . , eb serv
i;£ecycl• of HTTP Session ° mactivity. .,,
9,1.31• .
11.,tost servlet containers use a cookie to identifY a session .
_ 'The user's browser requests a serv let. ·
1_ The servlet container creates a session.
2
_ The servlet gives the session a unique ID.
3
_ The servlet sets a cookie in the browser with this ID.
4
· Let's say the servlet. then store's the user's name m. t h e session
.
5
_ The user
. .requests
th tl another
. servlet on the same server As part · 0£ h
6 cookie w1 1e session ID is sent back to the server. · t e request, the
7. Since the servlet container is told which session to use, it
. make it. av il bl
8. So servlet #2 can retrieve the user's name since we p t 1·t. h a a e again.
"Hi, Tushar. 11 ' u mt e session, and say,
9. The user close the browser without ending session.
above 10. After 30 minutes web server expires the session.
r are:
sto:re 9.1.4 Session Management Rules
eqUire Session typically have the following characteristics :
• Session represents a conversation between client and serv er.
[
Wo:rk • Information or state must be stored.
~thods • Session must execute on behalf of single client. They cannot b h db
than one client at the same time. e s are Y more
• Each ITTTP request must carry an identifier.

[::s •

Can be both transaction-aware and use security.
Use an up-to-date web-server framework to generate and manage the session
identifier token, as this will guarantee values that defy prediction.
• Take every precaution to ensure that the session identifier remains confidential to
~t ':11Y
~ss1on the application.
the • Session needs to have a timeout.
t as a
9.2 Session Tracking With Servlet API
Session tracking is a mechanism that servlets use to maintain state about a series of
citly. requests from the same user (that is, requests originating from the same browser) across
to it. some period of time. Sessions are shared among the servlets accessed by a client. This is
r the
convenient for applications made up of multiple servlets.
t. In The javax.servlet.http package contains a number of classes and interfaces that
· describe and define the contracts between a servlet class running under the HTfl' protocol
and the runtime environment provided for an instance of such a class by a conlornung
.
servlet container. .d tify cross more than one
The interface HttpSession provides a way to 1 en a user a
page request or visit to a Web site and to store information about
. that user. an HTTP chent
between .
u· d~ .sessionriod across more than one
and The servlet container uses this interface to create
an HITP server. The session persists for a spec ie tune pe ' d to one user who
connection or page request from the user. A session usually c~rrespon s such as 'using
may · · · · ·on in many ways
visit a site many times. The server can maintain a sessi
cookies or rewriting URLs.

lilmMl)lll!Ju§@
~~~
. J (T y.[J.Sc,-I.T,) (5P.m, 1
5e55/,on
£riterpnse ava · Vi
,..a~al'ltages
.,.,,..,.
, ervlets to:
.
th• session 1denlific, 1
. cookies red'llce
'J.,. Cookies tnai:n~
72 This interface allows s . t· n about a session, such as , . cookies help red~
• la Le 1nforrna 10·
~
V' and rnanipu lf 1 3
• iew_ rrnc and lasl accessed t1rne. . to persist across rnu ip e \ls(:1 t)isadvantages
creation • , . user information
1,. Cookies are not
• Bind objects to sessions, allowing can be exptes!ied~
connections.
9,2.1 l',{ethods of Session Tracking . used by the Web containet to ,:o~•
session Management is a rnechan!S!ll four different tecl:•r>;,ques us y
~~~ z..
.
Cookies are B.'r~
Cookies size. al\c
3 another.
· 1 r user rnere are
information for a particu a · t They are as follows: 11· Ilidden fonn fi
application for session rnanagernen · . .
I. Cookies .d used and accepted ways to maintam , 1n this techni.11'
1
Usll'g cookies is one ?f the 7,;'.::,'.J:';r ::,t your server generates and_ the bro:vser hal'l-dfu\g functiona
. A cookie is a special tag . ting of nallle-value paus assoe1ated be as sunple as at;
session.
accepts, A,ctually, it is a
with a URL, in this ~ase'.dt
";p"rr
. 1 data structure cons1s · h
~RL to e,<ecute the servlet. for ,nairltairring a sess1on, t '
and other session data as a text stnng in the cookie.
identification whe
application. The
serv et stores the session l en l ier k' the browser propagates the cookie
. . to your serv let browser until a
l the session
tingfrorn coo 1e,to the servlet. A servlet can read the cookie and browser to the s
After ace-:;.,, the browser
fo:de;''[.,";Jntents at any urne. If there is no cookie, the servlet detects a new session, identifier is a1s9
session for the i
,nener[tes a unique session identifier, and sets this value to the cookie. Tlus lS then sent
f,ck to the browser along with the response HTML page. The_ browser interprets the passes it as a hi~·,
response, identifies the cookie, an_d sets it irl the browser. After this, for every request, the Since this
browser sends this cookie contammg the sesswn ,denti/1er to the servlet. application \j
Cookies can be transient or persistent. The Transient cookies last until the browser is maintaining t1.J
closed, while persistent cookies are stored by the browser on the physical disk, to be a page outside
retrieved and used when the same URL is accessed by the user again. Cookies, transient or }ITMLfa
persistent, have a time limit and expire after the time limit is exceeded. <INP]
A primary limitation of cookies is the length of data that can be stored. A maximum This enb
of 4KB of data can be stored in a cookie. This limits the amount of session data that can be
included in j
stored for a user.
Browsers allow disablirlg of cookies. If cookie acceptance is disabled, this technique is
about the si
dynamica11)l
not going to work. For example, a servlet could do something like the following : general ses~
String sessionID = makeUniqueString( ); Advantage1
Hashtable sessionlnfo = new Hashtable( );
Hashtable globalTable = findTableStoringSessions( ); 1. HiddJI
even
globalTable.put(sessionID, sessionlnfo); meth
.
. sessionCookie
Cookie = new Cookie("JSESSIONID", sess10n!D)·
.
2. Hidd!
sessionCookie.setPath('1/"); '
wor~
response.addCookie(sessionCookie);
. _Then, in later requests the server could use the gl bal UL UR~
sesSion JD from the JSESSION!D cookie with the sessio':.infTable hash table to associate a . Wit
with that particular session This is
h f ·
°
hash table of data associated
an exce11ent solution and · th identifie~
approac or session handling. Still •t . . lS e most widely used that ses
handles all this plus the following ted:ou~ : ~ ~hat servlets have a higher-level API that

• Extracting the cookie that stores th . . jsessio


(there may be many cookies, after aui" session identifier from the other cookies
works
• Setting an appropriate expiration tim £ h . Bowe
• Associating the hash ·tables with e he or t e cookie. progr
• G . ac request to be
eneratmg the unique session identif·1ers. .

l":ml"Mll m>ut; l3
~~~
,\ih ,,olilt\''"
,11,~ 1,1,\lh•' 11, 11w,,1I• 11,1111, 11111q11111•d 111 IJl'l , ,·,•w ,lltr1>,,.
111111
1 , \' , 1 111111111 ,d ,1 ,,11, 1 11I d ,1111
I ( 1h t-
11 1
1
", t \,,1ld1':l l11'I\I 1,1d111 •1• l111 • 1 11111111,
1
-.lly .,, llll ,qtplli tt l l11 11 l11gi«

; lt11,hh•1ntlllt\''14 , 11111 1'l111•11n•, llwy 1'1111 l,p vl1•w11d 11Hd 1n11dllwd •md r,, ..-,,,r,n~i 1 1nfor r
t , 1 '" , ..• ' ,.,,
' •
'\ 1 411 11
,\\t\ \II' ,, 1n •r1111 11I. rna 1<,n
1 1
.' , \i,il-.kl'I ,111• 11'1 l'I' 1-1 111 1,•llk lllld tilt 1•11 11l11 1 1i,11•d tor• 11'1"1'11 r"'JIJn,t c,nly ,
l 1 1 ,1-h''I 1I ,t' ,\ll,11•11li'd 1111' 11 1'111 1 111 h1 ll11ill1 •d r111d vr1rl1•H from (Jn•• f'!i,~nt «p 1. •
,\ • "' p 1eattrm to
1 1
,n\111lw1·
ll, 11tihh•l\ 1\11 111 fl,•hl 1

\ti thl:i 1,1,•h11lq111 '; 1h1 1 dl1 v1•l11pt•1· ur1r11 11111 ·H 1•1•Hprnwibility for implerm.'1lting the &es.~jon-
h,H'dllnl', 1,111,11!111\l\lll y, 'l'lw 111 1 rvld p,1•111•1•:1 t, ·t1 ,, ramlorn icfontification for a client. Thi& can
l'I\' ,\ti :ihl)t1k iul 111•t111d11111 tH1111U\' I' p,1•111<1·11l1•d u11in~ 1hc Ja v"' APL The sl;!1"Vlet generateh thi&
hti,,illfl,•nll\HI wh1•11 llll' lop,icll l dknl t1ct-1ulo 11 111 i11lliulcd, say, by logging in to your servlet
,\l'l'lh'tilh"\, '1'111' :11 1 1·vll'l wl'llct-J thl t-1 ld1•11Ufkolio11 lo every page served to the client
,,, nv:ll'l' Hntll 1 h1p,1,11I lr1 \;t1ll1 1d hy lhl' dlvnt browi;cr. On every request sent by the
1
1briiw:ii'l' 11, tl\l' 14111·vl11 I for 1•x:11n plc, r;ubmir-mion of data in an HTML form, the session
hkntllkt' IH ,11111> 1w11l to llw 1-1c rvlct. 'l'hc t-icrv lcl uses this identifier to maintain a logical
:li'HH"hin tel1' th1• dl,,,1111. After p,·occl'l~'. ng llw Jc1tc1, lhl! servlet uses the same identifier and
pii:;:-i'H 11 11 hlJd11n vu lite In the 111 ML page:! sent lo the browser as a response.
1111
Sini·~' thlr; tcchnkptc ii, nC)l lied lo any j:lerver, it can be implemented fm any
'le ht'" '-•\\•11~r· ilpplk'nllon i,t'l'Vl'i'. 1 lowcv c r, the~ 1:.h-' v1•lop1•r bears responsibility for creating and
l l.l-3 !Si,.
' 1 lS mi,1nlt\lnlng t+w 1M•lHhll1 , Thl:-1 ll1 c hnicp11.! iH difficull lo implement. Also, if the user refers to
,, l\I
t l)

. t l\11'~l~l)t ()t pi,si' c)ut 1d"' th.• upplknlion, then lh{• ronh:xl is lost and the session can break.
11 11
l l'l'ML ft>rlllH cnn hove nn entry lh..il look'i like the following:
A nu1\inu1n, <INPUT TYPl1• "HIDOEN" NAME="1;cssion" VALUE=" ... ">
n thnt cnn l,, This c11lry ml'M\H thul, whl'll thl' form is bUbmittcd, the specified name and value are
indu(hl In tlw GET or POST data . Thi s hidden field can be used to store information
tc."chniqm' is nbout the Sl'SHion bul hmi the major disadvantage that it only works if every page is
g: dynnmlcolly generated by a form submisRion. Thus, hidden form fields cannot support
gcncml session tracking, <.>nly tracking within a specific series of operations.
Advantages and Disadvantages of Hidden Form Field
1. 1llddon form field mechanism is similflr to the URL rewriting mechanism, but works
t!vcn with the l lTfP POST method. This mechanism is not restricted to the GET
method only, we can also use the POST method without using path info.
2. Hidden form fidd mechanism also has some disadvantages For example it only
works when <Nery page is dynamically generated by a form submission.
Ill. URL Rewriting
. ~ith this approach, the client appends some extra data on the end of each URL that
itfonttfic11 the sesc;ion, and the server associates that identifier with data it has stored about
th0 t Sl'Hsion. For example,
., ~ilh litlp://lwM/pafh/jile.html;jsessionicl=5678, the session information is attached as
JscsSromd•5678. ThiH is also an excellent solution and even has the advantage that it
; orks when brnwscrs don 1t support cookies or when the user has disabled them.
1owever'haIt has most <>( the sam~ problems as cookies, namely, that '.h_e server-s1·de
program
to be 8 • lot of straightforward but tedious processing to do. In addition, you have
very careful that every URL that references your site and is returned to the user

C!t)RmRmlll!Ju§t;J
-~~~
([ Y.B.Sc.-I.T.) (Seni.,1,,
Enterprise Java . J

,. h the extra informati_~


74 ,,,.,,.., • JJ , ,wrvcr rPdirects). as bookrn.ark or link, t'L
. . t' n {w s in · b k via a 'l~
even by inJirc·cl nwnn"l 111<1• f,oUl t1Jo,. <;<'"l'>iot1 .inJ comes ac
(
nppcndcd. /\nJ, i'f ti w l J<!l'f k,tV<.'!:,
.
1 . to use and invo1ves ol\
session info1 m.1tio11 c,H1 bl' Jo1;t , . l of view, it's very ea!YL E~coding is that it's~
f coding poin c Jet U1, '' ~
Thr best p,Hl is th.it rorn l thing with :,crv d ' bled
URL ;\noth(•r goo, k' , 5 are 1sa ·
step encoding t I,c .. irks in only if browc,cr coo ie URL( ) method and if w~
follback approach ,,nd it k . HU ServletResponse encode want to provide sessiot\.
We c,in t•ncod<' UHL with p thcr resource and we
. I r •quest R to ano h Od
h,wc to . redirect. l w . , c ncode · e d'ire ctURL() rnet ·
will use URL rewn·t·ll'\t>0
information, we <.,,n use e . b e except that we . disabled
. ·1 roJect Jike a ov if cookies are ll\
We will crea te a s1m ar P 1 t works fine even
methods to make sure session managemen
browser.
Advantages of URL Rewriting £ d ta for a short period of time such as
. . all amount o a
1 · When
we need to maintain a tism reques t .
between two or three consecu ve_ . ta we can use the query string.
When we need to navigate a specific da
2. . . . d on each pages.
3. Extra form submission is not require
Disadvantages of URL Rewriting .
1. URL Rewriting can send only textual information.
2. URL Rewriting works only on links.
IV. HttpSession . . t extent by wrapping all the
The Servlet API simplifies sess1onHhanSe<llli:g toAPal ~::te maintenance between the
fun tionality. in the ttp server's .
ss10n setting a cookie in the client browser.
session-handling c
th
client browser and the servlet _is done by_ e .d tifi' enerated for different clients and
The server maintains a mappmg of session 1 en ers g .
· sm·ce this data is stored on the server side and only the
the data store d for each session. ki
identifier is passed back and forth between the client browser and the Server as a coo e,
this · method is also an example of server-side session handling. Servlet AP~ provides
Session management through HttpSession interface. We can get session ~om
HttpServletRequest object using following methods. HttpSession allows us to set ob1ects
as attributes that can be retrieved in future requests.
1. HttpSession getSession( ) : This method always returns a HttpSession object. It
returns the session object attached with the request, if the request has no session
attached, then it creates a new session and return it.
2. HttpSession getSession(boolean flag) : This method returns HttpSession object if
request has session else it returns null.
Some of the important methods of HttpSession are :
1. String getld( ) : Returns a string containing the unique identifier assi~ed to this
. 0
sessron.
2. Object getAttribute(String name) : Returns the object bound v.Tith the specified
name in this session, or null if no object is bound under the name. Some other
methods ~hlch . work with Sessi?n attri~utes are getAttributei'\James( ),
brl
to
re
removeAttribute(String name) and setAttribute(String name, Object value) .
3. long getCreationTime( ) : Returns the time when this session was created,
measured in milliseconds since midnight January 1, 1970 Gt\lT. We can get last
:~
accessed time with getLastAccessedTime() method. .

-
~ [:m]1(1]

~~~
lll!JU1.; l3
~
,,.,,,,A .• ,,,dn•ctivelnterval(int
set!"".. b f h interval)
1 :. Spedfi•••
·1 . the fo,w in "''"
r nt ,equests e ore t e serv et contame< w, I ,nvalidal•• .,this ,,~si•
, ,•x;t10~
~..,.Jn.o-;
.;, ·
"

~~
c ie ·on tiJl"«out value from getMaxlnactivelnLerual() nwthod "'· •' an Yl'i
. 1
5. serv!etC•"'""'
. getServletContext( ) : Returns Servl<•tC<,n"'/\
- ,
'"f"' f•n U \
does not yet ~ n•,w al,wt ti
I

apP}ication,
ole"' ;,New() : Returns tn1e 1£ . the cbent
.
6, :; if we client chooses notto join the session. ' " "' '"
7- .0 ·d invalidate(): Invalidates this session then unbinds any oblecb
, L•• " ,,, t,, ....
l
9.z.z ..Vllderstanding JSESSIONID Cookie
,,. "we use JlttpSerVietRequest getSession() method and it cr••atc', a.,.,.,,,. _,. 11
yvl'e,•th• new H ttp5 ess1on
. ob iect
' and al so a d d a Cookie to the rc-;p•,n".e ,,.,,.,,, tq,=n,
all'le JS-cssJONID
1·t creates
t1b·ect 1"
P
and vafr
. further requests
l ue as li
session
· If 1' d . This cookie
.
orn c ent. the cookies are disabled at cliPnt i;id" «r ,a
~
· is used to identify il ,, Htto'·.,
, ,,,,11....,1-,um
,,....,..., II J
, ,
- - • ' ' ,,,..
oJ lJRL rewriting then this method uses the jsessionid value from th•,,.,,,,,..,. u,1. b
us~gthe corresponding sessi?n- _JSESSIONID cooki~ is used for session trav , ,, .,, ,,;,
fin ld "•' use it £or our application purposes to avmd any session relat<ed i-,; ,c-s

5
hou p
_ _ SSL secure socket
(Secure LayerLayer)
Sockets (SSL).15 a standard
_ . protocol for establishing enety?re<
secunty
2 3
9. ks be~--een
)1" '.. a web se,ver and a browse, m an online communication. The u•a•= . ,,- ,, i,,
.•,~,
i. ..... oiogy ensures that all data transmitted between the web server and brovrs<ef •e~'' "'
tee••· · •· •·· ·
0
The S,SL protocol was original!Y developed by Netscape, to ensure 5<SCUrity ; C•ue
encrypted.
transported and routed through HTTP, LDAP or POP3 application layers. SSL is design.ED
the to ,na1<e use of TCP as a conununication layer to provide a reliable end-to-end secure a!lC
the authenticated connection between two points over a network such as service client aM
ser.
anct When an Internet user visits a secure web site, an SSL certificate ?TO #ts
the server.
the identification information about the web server and establishes an encrypted conrectior.
[ kie,
'fhls process happens in a fraction of a second.

r;:
[ides 1. A browser attempts to connect to a web site secured with SSL. The brow5"r
requests that the web server identify itself.
2. The server sends the browser a copy of its SSL certificate.
3. The browser checks wbether it truSts the SSL certificate. If so, it sends a message
t. It
sion
to theserver
4. The server.sends back a digitally signed acknowledgement to start ar SSl.

ct if
encrypted session.
5. Encrypted data is shared be!Ween the browser and the server.

this 9.2.4 Without


Workingsession
with Sessions
management, each tune a client makes a request to a server, it's a
brand new user with a brand new request from the server's point of view . A session refers
ied to the entire interaction between a client and a server from the time of the clients first
he! req~est, which generally begins the session, to the tune the session is termiru>ted. The
), ~•• n could be terminated by the client's request, or the server could automat1ca\l Yck)••
~r th
0 a certain period of time, Default technique for session tracking is to use co?kies.

ed, Cookies are sent in the header part of an HTI'P message, so they must be set in e
11
ast response prior to writing any data to the response .

• [ilmMD[ll!)ru;@
~~~
Enterprise Java (T.Y.B.Sc.-J,T.) (Sr111.~v)
76

1· Creating Session
To create a new session or gain access to an existing session, use lh~
HttpScrvletRequest method get5ession( ), as shown in the following exarnple:
HttpSession mySession = request.getSession( );
. The getSession() returns the valid session object associated with the request,
identified in the session cookie that is encapsulated in the request obJect. Calhng the
me d with no arguments creates a session if one does not exist that is associated w_ith
th0
lhe request. Additionally, calling the method with a Boolean argument creates a session
onJy 1f the argument is true. ·
IJ · Invalidating a Session
. Direct the session to invalidate itself automatically after being inactive for a defined
time period. Alternatively, invalidate the session manually with the HttpSession method
mvalidate( ).
To invalidate a session manually, simply call the following method:
session.invalidate( );
All objects bound to the session are removed.
· Session timeout is also possible to expire session after definite time interval passed
due to user in activity, which can be set using the session-timeout element in
the web.xml deployment descriptor file.

QUESTIONS
1. What are Sessions? Explain its types.
2. How to provide unique identifier in request and response?
3. Explain in short Session ID, Session expiry.
4. Elaborate Lifecycle of HTTP Session.
5. List and explain session management rules.
6. What is session tracking? What are the ways to track the sessions?
7. How to track session using Cookies?
8. How to track session using Hidden Form Fields?
9 How to track session using URL rewriting?
10. How to track session using HttpSession?
11 . Write short note on SSL.
12. Write short note on creation and invalidation of sessions.
use tl)~ CH AP TE R

• req lteSt
Ii..1 UN IT - II
ell
ling t-h,
ted '-vi ti
a ses sio t).

W O RK IN G W IT H
a defi n.eq
me tho q
FILES
method_.
• • • • •
• •
U pas sed.

rent ~ ~ 0.1 Uploading Files


Upioad is a term use d to des cribe
the process of transferring (sending
mp les of
) a file to
how a file
or net work. Below are a few exa
another computer thro ugh a mo dem
may be uploaded to another computer.
I :J Examples of an Up loa ded file : a file to
nected to a net wo rk you can upload
• Over a net wor k : If you are con
sha ring.
another computer or sha re usin g file rnet, or
r FTP , Tel net , or SSH : If you wa nt to share something on the Inte
• Ove or server
uld upl oad the files to a computer
have a personal web page, you wo oad ing files.
mo st com mo n me tho d of upl
connected to the Internet. FTP is the many web
por ting file upl oad s is a ver y basic and com mon req uire me nt for
Sup , so any web
on sup por ts file upl oad out of the box
applications. The Servlet 3.0 specificati and make mime
cation can par se mu ltip art requests
container that implements the specifi
pSe rvle tRe que st object.
attachments available thro ugh the Htt e that
ota tion , jav ax. ser vlet .an not atio n.MultipartConfig, is use d to indicat
A new ann art/ form-data
serv let on wh ich it is dec lare d exp ects req ues ts to ma de usi ng the mu ltip Part
the @MultipartConfig can retrieve the
vlet s tha t are ann ota ted wit h
MIME type. Ser t.getPart(String
pon ents of a giv en mu ltip art/ for m-d ata req ues t by calling the reques
com
name) or request.getParts() me tho d.
Important poi nts mons
lelt emF act ory is def aul t Fac tory class for File ltem . Wh en Apache com
1. DiskFi file content
Fileltem, this imp lem ent atio n kee p
read mu ltip art con ten t and gen era tes . By
mo ry or in dis k as tem por ary file, dep end ing upo n thre sho ld size
either in me por ary files
sho ld size of 10KB and gen era tes tem
default DiskFileltemFactory has thre
ry, retu rne d by Sys tem .ge tPr ope rty( "jav a.io .tmpdir").' Both of these
in temp· directo t use d for
are con figu rab le. You ma y t per mis sio n issu es if use r accoun
values p directory.
J .ier mis sio n to wri te file s into tem
running Ser ver doe sn't hav e sufficie
pin g larg e content in
2· Choose thre sho ld size car efu lly bas ed upo n me mo ry usa ge, kee
too small
ory ma y res ult in jav a.la ng. Ou tOfMemory exc eption, wh ile hav ing
mem
files.
values ma y res ult in lots of tem por ary

1:J:u1M11 lm1irta ID
lM ~ ~
,., v-1°1
•th files
JcitiS wi
.:::.h3;,,File Uplc
·se Java (T. Y.B.Sc.-1.T.J (Seni.,y)
£ 11 tcrprl Select a file tc
• . Tracker to delete tempora.ty <form action
,,.,,.., rovides fileClean•~g Tracker deletes temporcl.ty
78 a~:~rory.
he corrunons file u_Pload The fi1eClean:f1ected. lt accomplish this by
data">
<inputtyp
3. ~~=\reated Di'.kF~~~:;file
by 1ostan~•~l~:~:.g: Joaded. If _you use this fean,,,, <br />
files as soon as cott,~~h is created when F1l\n our web application ends. . <input tyJ
a cleaner thread w; rminate this Thread wh y ·,:num file size, threshold size etc
</form>
than rexncni.bct to e ·1 upload directory, ~ax1 th are not configured.
f blc deta1 s e.g. f lt values 1n case ey </body>
4. ~eep ~?;f~fe~r:nd use reaso1i.able de au h details of Files based upon y_o ur. project
t pe and ot er . of certain size an,i
~ </html>
111 c01 to .
._ d to validate size, Y now upload only images
s. It s goo may want to a j D i.u,

requiren1ent e.g. Yc;:G pNG etc.


certain types e.g. JP ' hich it is declared expects
M lti artConf ig
10.1.1 @ u p . . d t indicate that the Servlet on w d t annotate Fil
annotation .is use o d ata MIME type · We neeultio art/ form-datae
s the rnultipart/ form-
Thi
requests to rnade usrf with MultipartConfig annotation -to ~and~ :- ~otation has
~
Upload handle~ serv for uploading file to server. Multipart o ig -
requests that is use
following attributes :
I. fileSizeThreshold . th u load file temporarily. If the
This attribute Specify size threshold when _sav~g e pd . disk. Otherwise the file
upload file's size is greater than this threshold, it will be store m ~
To downloa
is stored in memory. Size in bytes. Defaults is 0 .. . network, saving
n. location · d fil are store d D e f ault "" · All sorts of
1
This attribute Specify directory where up oa es · For example, Y
Ill. maxFileSize d fil s· m . b yt es D e f aults lS
· -while you're m
This attribute Specify maximum size of an uploa e. i~e · computing cap]

-11. 10.2.1 ouect ~


IV. m.axRequestSize . The Duel
This attribute Specify maximum size of a request (including both upload files and
used -within t1
o_ther form data). Size in bytes. Defaults is -1L. that points to
used in con-v
10.1.2 Creating a File Upload Form
The following HTM coae below creates an uploader form. Following are the downloading
important points t~ be noted down while coding : the file is sto
• The form method attribute should be set to POST method and GET method farm.
cannot be used. Exampl


The form enctype attribute should be set to multipart/form-data.
The form action attribute should be set to a servlet file which would handle file
10.2.2 1nJ
uploading at backend server. Following example is using UploadServlet servlet to
servlet.
upload file. Ex
• .To upload a single file you should use a single <input .. J> tag with attribute
type="file". To allow multiple files uploading, include more than one input tags
with diff~rent values for the name attribute. The browser associates a Browse represent

button with each of them.


<html> 1. Writ
<head> 2. Whl
<title>File Uploading Form</title> 3. Hol
</head>
4. w
79
I Vr11~111.~ 11•,11, 1'1/t-:l

-...h:\'tlll,, \ lph,nd:-.. / h:\~


fkkt'l 11 111,, 1,111ph1111I: ·-hr/ '
-..fn1'n\ (\\' I Inn nuplt)l\,l~~rvkl" nwthod .-. ''post" cnctype = "multiparVform-
chtl,i11' 11
11
-.:inpul ty1w ~• ''l'lh.'" tu\t1W , "flk" ~\t.f' • 50 />
-... b1· / '
,input ty1w "~uhmll" vn lue n "Upland Pile"/>
,jfo1•m:--
,jbody >
</html>
X
f'l r"'1tlf\l,~tu\,>h~~, H ltt'f,••'
Pec::ts I
(,1 <I) 111-'J//('J\I••· ,.. "
~ File

.
01q~I~ • ~tt,~lett
-da ta > •~ln.1H "
J\ Muih..
has l

) llll Ph.li.fh
, .,...,
) Ii. I Ot":.11 i)l\t (Ci) "' CaptUff'I.
vi
r,..t\M'l,el L:,__. _ __..., Anflk:s

f the ~
e file
[10.2 Downloading Files
To download something on the Web means to transfer data from a website or
network, saving that information on your computer, tablet, or mobile device.
All sorts of information can be downloaded on the Web: books, movies, software, etc.
For example, you can download movies to your smartphone or mobile device to watch
Its is while you're on the go. Of you can download software or applications to increase your
computing capabilities.
10.2.1 Direct Link
and The Direct download link (ODL), alternatively simply direct download, is a term
used within the Internet-based file sharing community. It is used to describe a hyperlink
that points to a location within the Internet where the user can download a file. When

r the
used in conversation, DDL distinguishes itself from other forms of peer-to-peer (P2P)
downloading architectures in that it uses a client-server architecture, where 100-percent of
the file is stored on a single file server or in parallel across multiple file servers in a server
ethod
farm.
Example: http//mu.ac.in/portal/1.nformation-Technology.pdf

10.2.2 Indirect Link


e file The indirect link are not contain the real file name, this usually pents to a program or
let to
servlet.
Example : http//myserver.comfdownload?id=1234 . . .
• 1=-1,;,...,g because mstead of linking t O h •
We call this indirect, or semantic ·t UU\-U'. .
physically lives, • h
t at w ill b e sorted out ab P ysical
representation. lt doesn't matter w h ere 1 Y server.
QUESTIONS
. f'l1 w·th
1 1·ava Servlet.
1. Write short note on Uploading ·1 e }oadmg a file.
. 7

2. Which points are important w h 1 e up


3. How to create HTML upload form? .th . Servlet.
4. Write short note on Downloading file Wl Java ,,.,,.,,.
liOOXMJ)[ll!)u§@
~~~
.. 1,...,,-Bloc
•t/1. l"V"

F;nterpriY J«va (I , ( ,B.Sc.• J:f.) (Sem.~i,1


r;1or1'i,,,g ,()fl tvletRE
80 se othe·
to a:l'.l
vverocess1
sh<:
.4,
~other_
proce~s
contalfl
we

..
can
s. il11Plernej
case of
~, c1ea11-UF,
ettlng up'
1.1,3 S
I 1'0 activati
de on the re/
f!tO 1 show~
aJ:l'.lP e
~letCont ext
@O<'erride
tected void
pro
11.1 Introductio n J throws Serv1
; Jon-blocking I/ O v,as introduced in Servlet 3.1 to develop scalable applic~~ons. {
Servlet 3.0 allowed asynchrono us request processing, but the API al1owed only trad1hona] I I Get the P
I/0, which can restrict scalabilit'J of your application s. ln a typical application, String
Servletinpt ttStream is read in a while loop. However, if the incoming data is blocked or is
streamed slower, the server thread must 'Nait for the data The same situation can happen // Set the
if the data is written to Ser1letOutp utStTeam. respol
Ser,let 3.1 resolves the problem by adding event listeners : ReadListen er and I/ Get the CC!
WriteListener interfaces. You register these event listeners by using
tStream.setWriteListener. InputStr1
Servl.etlnputStream.sefReadListener and ServletOutpu
if (conte1
1he listeners have callback methods that are invoked when the content is available to
be read or that can be written without blocking. { I
The ma.in idea of these technologies is to avoid threads blocking. That's important respons
be.cause blocked threads waste resources, threads' memory and processor time during return;
threads c.ontext switching. So in some cases it's possible to increase servlet performanc e }
without any costs.
// Prepare
Blocking aJso makes your server vulnerable to thread starvation. Consider a server
with 200 threads in its thread pool If 200 requests for large content are received from slow Async
clients; then the entire server thread pool may be consumed by threads blocking to write Servlet1
content to those slow dients. Asynchronous IO allows the threads to be reused to handle out.set~
other requests while the slow clients are handled with minimal resources.
l11.2 How it works? J
The basic flow for a se.rvJet that caJJs an external REST service using an async HTTP Noteh
client (for example AsyncHttpClient) looks like this : anct set
1. first of all the servlet where we want to provide async support should have
@WebServlet annotation with asyru:Supp orted value as true.
Once ~
2 Since the actual work is to be delegated to another thread, we should have a c~ed bac'
thread pool implementation. We can create thread pool using Executors 8
~ Patche
framework and use servlet context listener to initiate the thread pool. first caU to
3, We need to get instance of AsyncCon text through ServletRequest.startAsync( )
method AsyncContext provides methods to get the ServletRequest and tl.., !hethea
. _ llS ll'\

~lm)u t;g]
~~~
81

. gwit/1 Nori-Blocki11g J/0 It )so provides method to forward the request


war/a II e object references. a
servietRespons ·n dispatch() method.
to another resource us1 g I • L3mcntation where we will do the heavy
,1 should have a Rur."lnab c C1111ple t obJ'cct to either dispatch the request to
4· vve •ocessing an d ti,en use . Async on exusing ServletResponse o b'iect. Once th e
pt other resource r write hresponse Jd 11 AsyncContext.complete ( ) meth o d to l et
O
an ·n is finished, we s ou ca . . .
processt g t s nc recessing is fm1shcd.
container know tha a ~ P . tation to the AsyncContext object to
We can add AsyncL1stener imp1ernenthis to provide error response to client in
s. implement callback methods,_we can us;hread processing. We can a1so do some
rror or timeout while async
case of e
dean-up activity here.
. u pa WriteListener
11.3 SettU1g .. ·t . ·mply a matter of starting asynchronous
To activate asynchronous wntmg, 1 1sl_s1t er to the output stream. The following
t and then adding your is en . d fr h
mode on the reques . b d to server static content obtame om t e .
shows how this can e one
exatnPle
5erv letContext :
@Override 'd· doGet(HttpServletRequest request, HttpServ1etResponse response)
protecte d vo1 .
PPlicatio throws ServletException, IOException
traditi lls.
ap Ol)aj
Plicati {/ / Get the path of the static resource to serve.
locked o11,
can h or IS·
appen
String info=request.getPathinfo( );
II Set the mime type of .the response . .
response.setContentType(getServletContext().getMimeType(mfo));
stener
by Us~d I/ Get the content as an input stream · .
mg InputStTeam content = getServletContext( ).getResowceAsStream(mfo);

available to .if (content==nu.11)


{
unportant response.sendError(404);
~ e during return;
erformance
//Prepare the async output
er a server AsyncContext async = request.startAsync( );
from slow ServletOutputStream out = response.getOutputStream( );
g to write
out.setWriteListener(new StandardDataStream(content,async,out));
to handle

Note how this method does not actually write any output, it simple finds the content
·and sets up aWriteListener instance to do the actually writing asynchronously.

ould have 11.4 Implementing a WriteListener


Once added to the OutputStream, the WriteListener method onWritePossible is
called back as soon as some data can be written and no other container thread is
~ispatched to handle the request or any async IO for it. The later condition means that the
frrS t call to onWritePossible is deferred until the thread calling ·doGet returns.
!hi The actual writing of data is done via the onWicitePossible callback and we can see
s m the StandardDataStream implementation used in the above example :
"''t~
ai.ocldnZ J/O
('Jlll'l-v
, ., pas wr'
j
rl<lriz i,.e 100,-
vJo ce t_,. ,,o the req u
Ofl f 1'fl.~l.,,....
oO to 1 ,,J'\g (assutnJ.l'
etl'.l t,loC~ a11
((I h vt ti.J:'lg a Rea ·"i
,,....1t 0 __, ieJllert
f ~~p d to itr1P1ernen
I i;........- v,1e 11ee o,.ode- Rea
priv,,tc fin,11 J11pu1S111•11111 r1111H•lll;
... c.,c1<-i'Pg_ pas t}:lree q
11rlv,1ll' (in,11 /\11y11t'Conll•xt ,l'l)'ll<'i ofl'v1 t:3t1o!l
prlvah• f111al S1•rv h•tOu t p11 tHlrt•.1t11 o11 t;
: ..,wrrief'
it1" r
taA.-vailable
ot'\va
1

.
I
A ,-1cC'ont◄•xl aft yn<, • ,A.lloataRead l~S
' (I tf-l trc•am ro11l1•11t, i;y • ofl .
~ttor is 1nvok
priv,111• •~t.,rnl,11 d I >111,1 ,t n •, 1111 npu • fkrvl<•tOutput'>tr•~am out) • oll -c
· va.io.lOP)(
't'flPort J
3
~ ()1't java.util.Qu
1J11.P t ·a-va.util.con~
this.l onll 1 11l • l 0111<•111; iJ11.P 0 r J lcl
1hh,.,1sy11c w,y nc; 'J:P.Po rt ·}ava"-serv ~
1 rt J·a-vaX-servl
this.out out; itl'lPO ·ava)(.servl
itl'\Port J
plublic void onWrilc P011aiblc() throwHJOE-xceptjon itl'll'°rt javaX .servlE
itl'lPort javax-servlJ
I
byte[ 1buffer • tlC W byteL4096l; . itl'lPort javax.serv i
// while we are able to write w ithout bJocJ<mg public c\aSS Read
private 5ervletlnJ
while(out.isReady( ))
private BttpServj
I int len=content.read(buffer); // read some content jnto the copy buffer ptl-vate A,syncCo
private Queue qJ
ReadListene-ri,
// If we are at EOF then complete
if (len &lt; O) l
input= in;
l res= r ;
async.complete();
ac = c;
return;
)
out. write(buffer,O,len); // write out the copy buffer.
public void o~
System.c
I
I StringBu
public void onError(Throwable t) intlen =
byte bl l
getServletContext().log("Async Error'',t); while (i
async.complete(); Strin•
} sb.aI
} .
queue
When called, the onWritePossible() method loops reading content from the resource )
input stream and writing it to the response output stream as long as the call to isReady() public voi,
indicates that the write can proceed without blocking. The 'magic' comes when isReady()
Syste·
returns false and breaks the loop, as in that situation the container will call
onWritePossible() again once writing can proceed and th;,_s to loop picks up from where
it broke to avoid blocking. I In
7rr _y .B .Sc.-I.T .-Er
''1'-------~--- -------
1 ·th Non-Blocking I/O ,i",r,r w
ce
""'""' '" the Joop has writte n all<ll'thc Acon~cn t, :1. ' _ca \l~ llw AsyncContcxt,comph:t(•( ,1)
d to finalize the request 1,an ing.. nu l 1·wt H 1l 1 11I<' conl<'nt hoH now hl'l•n Wl'illl•n
011
Jl1-eth bl eking (assuming the rl'c1d from Lhl' n'Hou1•n.• input 111n•,in1 d<w•.; not blqi v)
0
·tnout O - - •
wt ..... e .. ting a RcadListe11er \
1' 5 We
JJlll'need
1e,,. •· to irn p lcment the Read- List<,'."'
- - clnss, w 1
h kh p,,, for'"', l h•• r,•,,d ,, ,.,,., i; "" ,n-;;
1 . g mode. RcadL1stcncrlmpl 1mpkn1<•1\lH t-hl• R<•ic1dL11-1l.-11<-r inh rf H' 'J'l .
11-b oc I 11 ' • Illfi
k
1 .... tation has three callback methods :
110
• onDataAvailable is called when <laln cnn bl' read without blocking.
·iJ11.P1eme,,
• onAUDataRead is invoked when data for the current rcqu<~flt i!-1 compl<'t,•ly r••ad.
• onError is invoked if the request generates an error.

iJl'lport java.io.IOExcept~on;
import java.util.Queue;
import java.util.concurrent.LinkedBlockingQueue;
import javax.servlet.AsyncContext;
import javax.servlet.ReadListener;
import javax.servlet.ServletlnputStream;
import javax.servlet .Servle tOutpu tStream;
import javax.servlet.W riteListener;
import javax.servlet.http .HttpServ letResponse;
public class ReadListenerlmpl implements ReadListener {
J er • private ServletinputStream input.= null;
private HttpServletResponse res= null;
private AsyncContext_ac = null;
private Queue queue = new LinkedBlockingQueue( );.·
ReadListenerl~pl(ServletlnputStream in, HttpServletResponse r, AsyncContext c)

{
input= in;
res= r;
ac = c;

public void onDataAvailable( ) throws IOException l


System.out.println("Data is available");

StringBuilder sb = new StringBuilder( );


int len = -1;
byte b[] = new byte[1024];
while (input.isReady() && (l~n = input.read(b)) != -1) {
String data= new String(b, 0, len);
sh.append( data);

queue.add(sb.toString( ));

~ublic void onAllDataRead( ) throws IOException l


System.out.println("Data is all read");

II now all data are read, set up a WriteListener to write

?/f.Y.B ·Sc.-IT
• .-Enterpnse
· Java (Sem.-V)

(iOOlMl)ln!)u@;@
~~~
•,!.

11-r,-r,• Enterprise Jcwa (f. Y.B.Sc.-l.T.) (Sfflt.-v-1


84
ServletOutputStream output= res.getOutputStream( );
WriteListener write Listener = new WriteListenerlmpl(output, queue, ac);
output.setWriteListener(writeListener);

public void onError(final Throwable t) {


ac.complete( );
t.printStackTrace( );

QUESTIONS

1. What is Non-Blocking J/O?


2. Explain the working of Non-Blocking I/0.
What is the role of WriteListener in performing Non-Blocking IO? Explain with
3.
example.
What is the role of ReadListener in performing Non-Blocking 10? Explain \\'1th
4.
example.

Q REDMI NOTE 8 '


~~- · Al QUAD CAMERA ,
??:-:tNA''

You might also like