Download as pdf or txt
Download as pdf or txt
You are on page 1of 5

19.

13 cOOKIES
HTTP is statciess. This mcans that every HHTTP rcquest is diflerent from others Sometinnes it is
Cssary lo keep lrack of asequcnce of related requests sent by a cient to pertormsone designated
This is calicd seSsIOn Iackng. Cookies are one of the solutions to session tracking, A cookie s? [
Servlets 667
created by the
value)par
firstWime
A
server and is installed in the
forthe subsequent browser also maintains a list of client's browser when the client makes arequest
apart of HTTP requests. The cookics installcd in it and sends it to the server as
sequence related
of
requests. server can then casily identify that this request is a part of
This way, cookics provide
a
cervlet APIsupports cookies. an clegant to session tracking. The
Acookic is solution
is
created.using the
following constructor:represented using the javax . servlet .http.cookie class and
Cookie (String key, string
value)
Acookie is added by the addCookie() method of the class. Similarly, the
servercan get
all cookies sent by
tRequestclass. There are two
thc web browser using the HttpservletPesponse
getCookies () method of the HttpServie-
types of cookies in servBets, non-persistent cookies and persistent
skies. A non-peISIstent cOOKie is valid for a single sessionnamely
and it is removed each time the user closes
the browser. Apersistent cookie however is valid for multiple sessions and it IS not removed when the
user closesthe browser. Acookie can be defined as asmall piece of information that is persisted with
multiple client requests., 1I he following example illustrates the handling of servlet cookies.
1/index.html
<form action="servlet1" method="post">
Name:<input type="text" name="userNane "/><br />
<input type="submit" value="go"/>
</form>

1/FirstServlet.java
import java.io. *;
import javax.servlet.*;
import javax.servlet.http.*;
{
public class FirstServlet extends HttpServlet
request,
public void doPost (HttpServletRequest
HttpServletResponse response)

try
response.setCont.entType ("t.ext/html "):
response.getWriter(0:
PrintWriter out = "userName") ;
Paramet,er (
String n=request.get
out.print (Welcome "+n):
cookie
("uname", n);//Creating
Cookie ck=new Cookie
object (ck);//adding cookie in the
response. addcookie
respornse
//creating subnit button
action='servlet2
out.print ("<form
method='post'>"); valuo'qo "}:
type submit
out.print ("<input
out.print ("</form,"):
Qut.close();
out.printli (e):)
(Exception e) (System.
catch
7SecondServlet.java
import java.io. *;
import javax.servlet.*i
1mport javax.servlet. http.;
PuoliC class Second Servlet ext ends Ht tpServlet HttpservletResponse
publ ic void doPost
do (HttpServletReguest request,
try{ responae) (
response.setContentType("Lext/html )i
PrintWriter out = response.getWr iter0;
Cookie ckl)=request.get Cookies);
out.print ("Hello "+ck |0).getVa lue 0);
out.close ():
}catch (Exception e) (Syst em.out.println (e) ;}

<web-app>
<Servlets
<description>This is the description of my J2EE Component</description,
<£isplay-name> This is the display name of Iny J2EE Component</display-hames
Kservlet-name> Servletl</servlet-name>
<servlet-class>Firstservlet</servlet-class>
</servlet
<servlet
<descriptionThis is the description of my J}EE component</descriptions
<aisplay-name>This is the dispiay name of my J2EE component</display-tamey
<servlet-name>SecondServlet</servlet-name>
servlet-class>SecondServlet</servlet-class>
</servlet>
<servet-mapping>
servlet-name>Servlet1</servlet-name>
Furl-pattern/servlet1</url-pattern>
/servlet-napping>
servlet-mapping>
servlet-name>SecondServlet</servlet-name>
url-pattern>/servlet2</url-pattern>
iservlet-napping>
welcone-file-list>
welcone-file>index.html</welcome-file>
/welcome- file-list>
Iweb-app>

The output willbe as follows:


htp://localhost:8080/cookie!
n localhost08)/caokie!

Latest Heedline: SacrededHeart College NOTES-ME CSE JDBC Tutonat Statene


Narne: Sacred Heart College
99
Latest htlp:/ ocalhost OR0/co6e/serletl
locahost 0)lieeitI Sorvtets \669

Welcome HeadlSacredines
go
Sacred Hean Colteqt
Met College

Hrelox

Latest Hedlines htp:/ocalhost:8080/co ke/serviet)


localhost 8080orkienlet)
Hello Sacred Heat Sacred Hean College
College NOTES ME CSE T JDRC
Tutofat tatene.

19.13.1 Limitations of Cookies


Cookies work correctly proVided the web
rity concerns, there are some technical browsers have enabled cookie support. In addition to the secu
limitations:
" Cookies can carry small
pieces of information and are not a standard means of
. Some web browsers limit the
number of cookies in general to 20 per web server.communication.
To avoid this prob
lem, more than one block of information may be sent per
cookie.
" The value of a cookie should never exceed 4 KB. If the value of a
cookie is larger than 4 KB, itshould
be trimmed to fit.
Cookies cannot identify a particular user. Auser can be identified by acombination of user account,
browser, and computer. So, users who have multiple accounts and use multiple computers/browsers
have multiple sets of cookies. Consequently,cookies cannot differentiate between multiple browsers
running on a single computer.
*Intruders can snoop, steal cookies, and attack sessions. This is called session hijacking.

19.14 FILTERS
between the client and the server to inspect requests and responses.
Filters are objects that are installed
the response or
both. The filterS are not servlets and hence can-
Ihey can transform the request or modify
before they reach a servlet and/or process responses
not create actual responses. Filtersprocessrequests following:
can do the
after leaving a servlet. In general, afilter
before dispatchingtotheservlets.
requests
IntModiercept
and inspect
fy requests headers and data and discard or
filter requests.
dispatching responscs.
responses before discard or
filter Similarly, zero or
Intercept and inspect servlets.
" Modify requests' headers and data
and
servlct
of
or a groupfollowingarcas: more fih.
behalf of a single
typicallyuscdinthe
Afilter can work on
installed for a scrvlct. Filters are
can be
" Authentication
Logging and auditing
Image compression
" Data compression
Encryption
a
" Tokenization
which provides
" XML transfornation

Afilter class must implement the


Filter interface,
javax.servlet. to be implemented by
methods
each frarnework
filter clas: f:
mechanism. It dcfines the following
the filtering (FilterConfig config)
void.init and to
once to install it set its
methodCOnfg.
callsthis method This
filter, servicing.
instantiating a start take
The web container, after successfully; thefilter can then configurethe filter. The
ration object. The method
Filterconfig object that
completcs
contains
used to
informationthat may beinitialization parameters which are
name,
Pilterir
specife
methods to retrievethe filter's
fig interface provides
xml file andthe underlving servlet context.
ServletResponse response, FilterChain chain
in the web.
(ServletRequest request,
void doFilter filter. It takes
from the client is passedthrough the xesponse threg
and
method is called every time arequest ServletResponse lype object
This
type object reguest, a request ar
arguments: A servlet Request
request and response objects encapsulate the client for
FilterChain type object chain. The represents the next filter in this chain of filters installed
chain
response respectively whereas this method is as follows:
implementation of
servlet. The usual
processes the request and takes the neceSsary actions, for exan.
Upon receiving the client request, it header etc. to the extent it can. The filter shouldthen hand ox
content or
ple, changing/formatting the by calling the doFilter() method on
chain. The next flter
the control to the next filter,in this chain client reques:
actions and forwards the request to the next filter in the chain. This way the
takes further filter in the chain, the doFilter () on
the chain
there is no further
is propogated towards the servlet. If
forwards the request to the servlet.
Chain of filters

init(...) { init(...) { init(..)


request service(...)
doFilter(...) { doFilter(,..) doFilter(..) {

Web
container
<o response
destroy() { destroy() f destroy() i
}
Filter Filter Filter Servlet

Figure 19.5: Function of filters

You might also like