You are on page 1of 19

Q:Explain the life cycle methods of a Servlet.

A:The javax.servlet.Servlet interface defines the three methods known as life-cycle


method.
public void init(ServletConfig config) throws ServletException
public void service( ServletRequest req, ServletResponse res) throws
ServletException, IOException
public void destroy()
First the servlet is constructed, then initialized wih the init() method.
Any request from client are handled initially by the service() method before delegating
to thedoXxx() methods in the case of HttpServlet.

The servlet is removed from service, destroyed with the destroy() methid, then
garbaged collected and finalized.

%!

Q:What is the difference between the getRequestDispatcher(String path) method


of javax.servlet.ServletRequest interface and javax.servlet.ServletContext
interface?
A:The getRequestDispatcher(String path) method of javax.servlet.ServletRequest interface
accepts parameter the path to the resource to be included or forwarded to, which can be
relative to the request of the calling servlet. If the path begins with a "/" it is interpreted
as relative to the current context root.

The getRequestDispatcher(String path) method of javax.servlet.ServletContext interface
cannot accepts relative paths. All path must sart with a "/" and are interpreted as relative
to curent context root.

%!

Q:Explain the directory structure of a web application.


A:The directory structure of a web application consists of two parts.
A private directory called WEB-INF
A public resource directory which contains public resource folder.

WEB-INF folder consists of
1. web.xml
2. classes directory
3. lib directory

%!

Q:What are the common mechanisms used for session tracking?


A:Cookies
SSL sessions
URL- rewriting

%!

Q:Explain ServletContext.
A:ServletContext interface is a window for a servlet to view it's environment. A servlet can
use this interface to get information such as initialization parameters for the web
applicationor servlet container's version. Every web application has one and only one
ServletContext and is accessible to all active resource of that application.

%!

Q:What is preinitialization of a servlet?


A:A container doesnot initialize the servlets ass soon as it starts up, it initializes a servlet
when it receives a request for that servlet first time. This is called lazy loading. The
servlet specification defines the <load-on-startup> element, which can be specified in the
deployment descriptor to make the servlet container load and initialize the servlet as
soon as it starts up. The process of loading a servlet before any request comes in is
called preloading or preinitializing a servlet.

[ Received from Amit Bhoir ] %!

Q:What is the difference between Difference between doGet() and do!ost()?


A:A doGet() method is limited with 2k of data to be sent, and doPost() method doesn't
have this limitation. A request string for doGet() looks like the following:
http://www.allapplabs.com/svt1?p1=v1&p2=v2&...&pN=vN
doPost() method call doesn't need a long text tail after a servlet name in a request. All
parameters are stored in a request itself, not in a request string, and it's impossible to
guess the data transmitted to a servlet only looking at a request string.

[ Received from Amit Bhoir ] %!

Q:What is the difference between HttpServlet and GenericServlet?


A:A GenericServlet has a service() method aimed to handle requests. HttpServlet extends
GenericServlet and adds support for doGet(), doPost(), doHead() methods (HTTP 1.0)
plus doPut(), doOptions(), doDelete(), doTrace() methods (HTTP 1.1).
Both these classes are abstract.

[ Received from Amit Bhoir ] %!

Q:What is the difference between ServletContext and ServletConfig?


A:ServletContext: Defines a set of methods that a servlet uses to communicate with its
servlet container, for example, to get the MIME type of a file, dispatch requests, or write
to a log file.The ServletContext object is contained within the ServletConfig object, which
the Web server provides the servlet when the servlet is initialized

ServletConfig: The object created after a servlet is instantiated and its default
constructor is read. It is created to pass initialization information to the servlet.

[ Received from Sivagopal Balivada ]

1 Q What is the difference between JSP and Servlets ?


A SP is used mainly for presentation only. A JSP can only be HttpServlet that means
the only supported protocol in JSP is HTTP. But a servlet can support any protocol like
HTTP, FTP, SMTP etc.


2 Q What is difference between custom JSP tags and beans?
A Custom JSP tag is a tag you defined. You define how a tag, its attributes and its body
are interpreted, and then group your tags into collections called tag libraries that can
be used in any number of JSP files. To use custom JSP tags, you need to define three
separate components: the tag handler class that defines the tag's behavior ,the tag
library descriptor file that maps the XML element names to the tag implementations
and the JSP file that uses the tag library
JavaBeans are Java utility classes you defined. Beans have a standard format for Java
classes.You use tags
Custom tags and beans accomplish the same goals -- encapsulating complex behavior
into simple and accessible forms. There are several differences:
Custom tags can manipulate JSP content; beans cannot. Complex operations can be
reduced to a significantly simpler form with custom tags than with beans. Custom
tags require quite a bit more work to set up than do beans. Custom tags usually
define relatively self-contained behavior, whereas beans are often defined in one
servlet and used in a different servlet or JSP page. Custom tags are available only in
JSP 1.1 and later, but beans can be used in all JSP 1.x versions.


3 Q What are the different ways for session tracking?
A Cookies, URL rewriting, HttpSession, Hidden form fields


4 Q What mechanisms are used by a Servlet Container to maintain session information?
A Cookies, URL rewriting, and HTTPS protocol information are used to maintain session
information


5 Q Difference between GET and POST
A In GET your entire form submission can be encapsulated in one URL, like a hyperlink.
query length is limited to 255 characters, not secure, faster, quick and easy. The data
is submitted as part of URL.

In POST data is submitted inside body of the HTTP request. The data is not visible on
the URL and it is more secure.

6 Q What is session?
A The session is an object used by a servlet to track a user's interaction with a Web
application across multiple HTTP requests. The session is stored on the server.


7 Q What is servlet mapping?
A The servlet mapping defines an association between a URL pattern and a servlet. The
mapping is used to map requests to Servlets.


8 Q What is servlet context ?
A The servlet context is an object that contains a information about the Web application
and container. Using the context, a servlet can log events, obtain URL references to
resources, and set and store attributes that other servlets in the context can use.


9 Q What is a servlet ?
A servlet is a java program that runs inside a web container.


10 Q Can we use the constructor, instead of init(), to initialize servlet?
A Yes. But you will not get the servlet specific things from constructor. The original
reason for init() was that ancient versions of Java couldnt dynamically invoke
constructors with arguments, so there was no way to give the constructor a
1.What Is the ServIet!
ServletConfig. That no longer applies, but servlet containers still will only call your no-
arg constructor. So you wont have access to a ServletConfig or ServletContext.


12 Q How many JSP scripting elements are there and what are they?
A There are three scripting language elements: declarations, scriptlets, expressions.


13 Q How do I include static files within a JSP page?
A Static resources should always be included using the JSP include directive. This way,
the inclusion is performed just once during the translation phase.


14 Q How can I implement a thread-safe JSP page?
A You can make your JSPs thread-safe adding the directive <%@ page
isThreadSafe="false" % > within your JSP page.


15 Q What is the difference in using request.getRequestDispatcher() and
context.getRequestDispatcher()?
A n request.getRequestDispatcher(path) in order to create it we need to give the
relative path of the resource. But in resourcecontext.getRequestDispatcher(path) in
order to create it we need to give the absolute path of the resource.


16 Q What are the lifecycle of JSP?
A When presented with JSP page the JSP engine does the following 7 phases.
o Page translation: -page is parsed, and a java file which is a servlet is created.
o Page compilation: page is compiled into a class file
o Page loading : This class file is loaded.
o Create an instance :- Instance of servlet is created
o jspInit() method is called
o *jspService is called to handle service calls
o *jspDestroy is called to destroy it when the servlet is not required.


17 Q What are context initialization parameters?
A Context initialization parameters are specified by the <context-param> in the
web.xml file, these are initialization parameter for the whole application.


18 Q What is a Expression?
A Expressions are act as place holders for language expression, expression is evaluated
each time the page is accessed. This will be included in the service method of the
generated servlet.


19 Q What is a Declaration?
A It declares one or more variables or methods for use later in the JSP source file. A
declaration must contain at least one complete declarative statement. You can declare
any number of variables or methods within one declaration tag, as long as semicolons
separate them. The declaration must be valid in the scripting language used in the
JSP file. This will be included in the declaration section of the generated servlet.


20 Q What is a Scriptlet?
A A scriptlet can contain any number of language statements, variable or expressions
that are valid in the page scripting language. Within scriptlet tags, you can declare
variables to use later in the file, write expressions valid in the page scripting
language, use any of the JSP implicit objects or any object declared with a
<jsp:useBean>. Generally a scriptlet can contain any java code that are valid inside
a normal java method. This will become the part of generated servlet's service
method.
A servlet Is a Java programmIng language class that Is used to extend the capabIlItIes of servers that
host applIcatIons accessed by means of a request response programmIng model.

2.What are the new features added to ServIet 2.5!


ollowIng are the changes Introduced In Servlet 2.5:
O A new dependency on J2SE 5.0
O Support for annotatIons
O oadIng the class
O Several web.xml convenIences
O A handful of removed restrIctIons
O Some edge case clarIfIcatIons

Learn more about Servlets 2.5 features

3.What are the uses of ServIet!


%ypIcal uses for H%%! Servlets Include:
O !rocessIng and/or storIng data submItted by an H% form.
O !rovIdIng dynamIc content, e.g. returnIng the results of a database query to the clIent.
O A Servlet can handle multIple request concurrently and be used to develop hIgh performance
system
O anagIng state InformatIon on top of the stateless H%%!, e.g. for an onlIne shoppIng cart
system whIch manages shoppIng carts for many concurrent customers and maps every request
to the rIght customer.

4.What are the advantages of ServIet over CCI!
Servlets have several advantages over CC:
O A Servlet does not run In a separate process. %hIs removes the overhead of creatIng a new
process for each request.
O A Servlet stays In memory between requests. A CC program (and probably also an extensIve
runtIme system or Interpreter) needs to be loaded and started for each CC request.
O %here Is only a sIngle Instance whIch answers all requests concurrently. %hIs saves memory and
allows a Servlet to easIly manage persIstent data.
O Several web.xml convenIences
O A handful of removed restrIctIons
O Some edge case clarIfIcatIons

5.What are the phases of the servIet IIfe cycIe!


%he lIfe cycle of a servlet consIsts of the followIng phases:
O ServIet cIass IoadIng : or each servlet defIned In the deployment descrIptor of the Web
applIcatIon, the servlet contaIner locates and loads a class of the type of the servlet. %hIs can
happen when the servlet engIne Itself Is started, or later when a clIent request Is actually
delegated to the servlet.

O ServIet InstantIatIon : After loadIng, It InstantIates one or more object Instances of the servlet
class to servIce the clIent requests.

O InItIaIIzatIon (caII the InIt method) : After InstantIatIon, the contaIner InItIalIzes a servlet
before It Is ready to handle clIent requests. %he contaIner InItIalIzes the servlet by InvokIng Its
InIt() method, passIng an object ImplementIng the ServletConfIg Interface. n the InIt()
method, the servlet can read confIguratIon parameters from the deployment descrIptor or
perform any other onetIme actIvItIes, so the InIt() method Is Invoked once and only once by
the servlet contaIner.

O Pequest handIIng (caII the servIce method) : After the servlet Is InItIalIzed, the contaIner may
keep It ready for handlIng clIent requests. When clIent requests arrIve, they are delegated to
the servlet through the servIce() method, passIng the request and response objects as
parameters. n the case of H%%! requests, the request and response objects are
ImplementatIons of HttpServletFequest and HttpServletFesponse respectIvely. n the
HttpServlet class, the servIce() method Invokes a dIfferent handler method for each type of
H%%! request, doCet() method for CE% requests, do!ost() method for !S% requests, and so
on.

O PemovaI from servIce (caII the destroy method) : A servlet contaIner may decIde to remove a
servlet from servIce for varIous reasons, such as to conserve memory resources. %o do thIs, the
servlet contaIner calls the destroy() method on the servlet. nce the destroy() method has
been called, the servlet may not servIce any more clIent requests. Now the servlet Instance Is
elIgIble for garbage collectIon
%he lIfe cycle of a servlet Is controlled by the contaIner In whIch the servlet has been
deployed.

6.Why do we need a constructor In a servIet If we use the InIt method!


Even though there Is an InIt method In a servlet whIch gets called to InItIalIze It, a constructor Is stIll
requIred to InstantIate the servlet. Even though you as the developer would never need to explIcItly
call the servlet's constructor, It Is stIll beIng used by the contaIner (the contaIner stIll uses the
constructor to create an Instance of the servlet). Just lIke a normal !J (plaIn old java object) that
mIght have an InIt method, It Is no use callIng the InIt method If you haven't constructed an object to
call It on yet.

7.How the servIet Is Ioaded!


A servlet can be loaded when:
O Irst request Is made.
O Server starts up (autoload).
O %here Is only a sIngle Instance whIch answers all requests concurrently. %hIs saves memory and
allows a Servlet to easIly manage persIstent data.
O AdmInIstrator manually loads.

8.How a ServIet Is unIoaded!


A servlet Is unloaded when:
O Server shuts down.
O AdmInIstrator manually unloads.

.What Is ServIet Interface!


%he central abstractIon In the Servlet A! Is the Servlet Interface. All servlets Implement thIs Interface,
eIther dIrectly or , more commonly by extendIng a class that Implements It.

Note: Most Servlets, however, extend one o] the stcndcrd mplementctons o] thct
nter]cce, ncmelyjavax.servlet.GenericServlet and javax.servlet.http.HttpServlet.

10.What Is the CenerIcServIet cIass!


CenerIcServlet Is an abstract class that
Implements the Servlet Interface and the
ServletConfIg Interface. n addItIon to the
methods declared In these two Interfaces,
thIs class also provIdes sImple versIons of
the lIfecycle methods InIt and destroy, and
Implements the log method declared In the
ServletContext Interface.
Note: Ths clcss s known cs yenerc
servlet, snce t s not spec]c to cny
protocol.

11.What's the dIfference between CenerIcServIet and HttpServIet!


CenerIcServIet HttpServIet
%he CenerIcServlet Is an abstract class that Is extended
by HttpServlet to provIde H%%! protocolspecIfIc
methods.
An abstract class that sImplIfIes wrItIng H%%! servlets. t
extends the CenerIcServlet base class and provIdes an
framework for handlIng the H%%! protocol.
%he CenerIcServlet does not Include protocolspecIfIc
methods for handlIng request parameters, cookIes,
sessIons and settIng response headers.
%he HttpServlet subclass passes generIc servIce method
requests to the relevant doCet() or do!ost() method.
CenerIcServlet Is not specIfIc to any protocol. HttpServlet only supports H%%! and H%%!S protocol.

12.Why Is HttpServIet decIared abstract!


!eople who read this, also read:-
PEW IntervIew uestIons
SF uestIons
SCEA CertIfIcatIon
HIbernate Vs IatIs
SP IntervIew uestIons
%he HttpServlet class Is declared abstract because the default ImplementatIons of the maIn servIce
methods do nothIng and must be overrIdden. %hIs Is a convenIence ImplementatIon of the Servlet
Interface, whIch means that developers do not need to Implement all servIce methods. f your servlet
Is requIred to handle /oGet() requests for example, there Is no need to wrIte a/oPost() method too.

13.Can servIet have a constructor !


ne can defInItely have constructor In servlet.Even you can use the constrctor In servlet for
InItIalIzatIon purpose,but thIs type of approch Is not so common. You can perform common operatIons
wIth the constructor as you normally do.%he only thIng Is that you cannot call that constructor
explIcItly by the new keyword as we normally do.n the case of servlet, servlet contaIner Is responsIble
for InstantIatIng the servlet, so the constructor Is also called by servlet contaIner only.

14.What are the types of protocoIs supported by HttpServIet !


t extends the CenerIcServlet base class and provIdes a framework for handlIng the H%%! protocol. So,
HttpServlet only supports H%%! and H%%!S protocol.

15.What Is the dIfference between doCet() and doPost()!


# doCet() doPost()

n doCet() the parameters are appended to the
UF and sent along wIth header InformatIon.
n do!ost(), on the other hand wIll (typIcally) send
the InformatIon through a socket back to the
webserver and It won't show up In the UF bar.
2
%he amount of InformatIon you can send back
usIng a CE% Is restrIcted as UFs can only be
024 characters.
You can send much more InformatIon to the server
thIs way and It's not restrIcted to textual data
eIther. t Is possIble to send fIles and even bInary
data such as serIalIzed Java objects!
J
doCet() Is a request for InformatIon; It does not
(or should not) change anythIng on the server.
(doCet() should be Idempotent)
do!ost() provIdes InformatIon (such as placIng an
order for merchandIse) that the server Is expected
to remember
4 !arameters are not encrypted !arameters are encrypted
5
doCet() Is faster If we set the response content
length sInce the same connectIon Is used. %hus
IncreasIng the performance
do!ost() Is generally used to update or post some
InformatIon to the server.do!ost Is slower
compared to doCet sInce do!ost does not wrIte
the content length
6
doCet() should be Idempotent. I.e. doget should
be able to be repeated safely many tImes
%hIs method does not need to be Idempotent.
peratIons requested through !S% can have sIde
effects for whIch the user can be held
accountable.
7
doCet() should be safe wIthout any sIde effects
for whIch user Is held responsIble
%hIs method does not need to be eIther safe
8 t allows bookmarks. t dIsallows bookmarks.

16.When to use doCet() and when doPost()!


Always prefer to use CE% (As because CE% Is faster than !S%), except mentIoned In the followIng
reason:
O f data Is sensItIve
O ata Is greater than 024 characters
O f your applIcatIon don't need bookmarks.

17.How do I support both CET and PDST from the same ServIet!
%he easy way Is, just support !S%, then have your doCet method call your do!ost method:

public void doGet(HttpServletRequest request,


HttpServletResponse response)
throws ServletException, IOException
{
doPost(request, response);
}

18.ShouId I overrIde the servIce() method!


We never overrIde the servIce method, sInce the H%%! Servlets have already taken care of It . %he
default servIce functIon Invokes the doXXX() method correspondIng to the method of the H%%!
request.or example, If the H%%! request method Is CE%, doCet() method Is called by default. A
servlet should overrIde the doXXX() method for the H%%! methods that servlet supports. 8ecause H%%!
servIce method check the request method and calls the approprIate handler method, It Is not necessary
to overrIde the servIce method Itself. nly overrIde the approprIate doXXX() method.

1.How the typIcaI servIet code Iook IIke !

20.What Is a servIet context object!


A servlet context object contaIns the InformatIon about the Web applIcatIon of whIch the servlet Is a
part. t also provIdes access to the resources common to all the servlets In the applIcatIon. Each Web
applIcatIon In a contaIner has a sIngle servlet context assocIated wIth It.

21.What are the dIfferences between the ServIetConfIg Interface and the ServIetContext Interface!
ServIetConfIg ServIetContext
%he ServletConfIg Interface Is Implemented by the
servlet contaIner In order to pass confIguratIon
InformatIon to a servlet. %he server passes an object
that Implements the ServletConfIg Interface to the
servlet's InIt() method.
A ServletContext defInes a set of methods that a servlet
uses to communIcate wIth Its servlet contaIner.
%here Is one ServletConfIg parameter per servlet.
%here Is one ServletContext for the entIre webapp and
all the servlets In a webapp share It.
%he paramvalue paIrs for ServletConfIg object are
specIfIed In the InItparam wIthIn the servlet tags
In the web.xml fIle
%he paramvalue paIrs for ServletContext object are
specIfIed In the contextparam tags In the web.xml
fIle.

22.What's the dIfference between forward() and sendPedIrect() methods!


forward() sendPedIrect()
A forward Is performed Internally by the servlet.
A redIrect Is a two step process, where the web
applIcatIon Instructs the browser to fetch a second UF,
whIch dIffers from the orIgInal.
%he browser Is completely unaware that It has taken
place, so Its orIgInal UF remaIns Intact.
%he browser, In thIs case, Is doIng the work and knows
that It's makIng a new request.
Any browser reload of the resultIng page wIll sImple
repeat the orIgInal request, wIth the orIgInal UF
A browser reloads of the second UF ,wIll not repeat
the orIgInal request, but wIll rather fetch the second
UF.
8oth resources must be part of the same context (Some
contaIners make provIsIons for crosscontext
communIcatIon but thIs tends not to be very portable)
%hIs method can be used to redIrect users to resources
that are not part of the current context, or even In the
same domaIn.
SInce both resources are part of same context, the
orIgInal request context Is retaIned
8ecause thIs Involves a new request, the prevIous
request scope objects, wIth all of Its parameters and
attrIbutes are no longer avaIlable after a redIrect.
(7arIables wIll need to be passed by vIa the sessIon
object).
orward Is margInally faster than redIrect.
redIrect Is margInally slower than a forward, sInce It
requIres two browser requests, not one.

23.What Is the dIfference between the IncIude() and forward() methods!


IncIude() forward()
%he #equestDispatcherinclu/e() method Inserts the
the contents of the specIfIed resource dIrectly In the
flow of the servlet response, as If It were part of the
callIng servlet.
%he #equestDispatcher1orwar/() method Is used to
show a dIfferent resource In place of the servlet that
was orIgInally called.
f you Include a servlet or JS! document, the Included
resource must not attempt to change the response
status code or H%%! headers, any such request wIll be
Ignored.
%he forwarded resource may be another servlet, JS! or
statIc H% document, but the response Is Issued under
the same UF that was orIgInally requested. n other
words, It Is not the same as a redIrectIon.
%he inclu/e() method Is often used to Include common
boIlerplate text or template markup that may be
Included by many servlets.
%he 1orwar/() method Is often used where a servlet Is
takIng a controller role; processIng some Input and
decIdIng the outcome by returnIng a partIcular response
page.

!eople who read this, also read:-


AAX IntervIew uestIons
SF Tomahawk Tag Peference
SChA0 CertIfIcatIon
AAX Form VaIIdatIon UsIng 0WP and SprIng
24.What's the use of the servIet wrapper
cIasses!!
%he HttpServlet#equestWrapper and HttpServlet#esponseWrapper classes are desIgned to make It
easy for developers to create custom ImplementatIons of the servlet request and response types. %he
classes are constructed wIth the standard HttpServlet#equest and HttpServlet#esponse Instances
respectIvely and theIr default behavIour Is to pass all method calls dIrectly to the underlyIng objects.

25.What Is the dIrectory structure of a WAP fIIe!

26.What Is a depIoyment descrIptor!


A deployment descrIptor Is an X document wIth an .xml extensIon. t defInes a component's
deployment settIngs. t declares transactIon attrIbutes and securIty authorIzatIon for an enterprIse
bean. %he InformatIon provIded by a deployment descrIptor Is declaratIve and therefore It can be
modIfIed wIthout changIng the source code of a bean.
%he JavaEE server reads the deployment descrIptor at run tIme and acts upon the component
accordIngly.

27.What Is the dIfference between the getPequest0Ispatcher(StrIng path) method of


javax.servIet.ServIetPequest Interface and javax.servIet.ServIetContext Interface!
0C IntervIew uestIons
ServIetPequest.getPequest0Ispatcher(StrIng path) ServIetContext.getPequest0Ispatcher(StrIng path)
%he et#equestDispatcher(Strinpath) method
ofjavax.servlet.Servlet#equest Interface accepts
parameter the path to the resource to be Included or
forwarded to, whIch can be relatIve to the request of
the callIng servlet. f the path begIns wIth a "/" It Is
Interpreted as relatIve to the current context root.
%he et#equestDispatcher(Strinpath) method
ofjavax.servlet.ServletContext Interface cannot
accept relatIve paths. All path must start wIth a "/" and
are Interpreted as relatIve to current context root.

28.What Is preInItIaIIzatIon of a servIet!


A contaIner does not InItIalIze the servlets as soon as It starts up, It InItIalIzes a servlet when It
receIves a request for that servlet fIrst tIme. %hIs Is called lazy loadIng. %he servlet specIfIcatIon
defInes the element, whIch can be specIfIed In the deployment descrIptor to make the servlet
contaIner load and InItIalIze the servlet as soon as It starts up. %he process of loadIng a servlet before
any request comes In Is called preloadIng or preInItIalIzIng a servlet.

2.What Is the Ioad-on-startup> eIement!


%he loa/onstartup element of a deployment descrIptor Is used to load a servlet fIle when the
server starts Instead of waItIng for the fIrst request. t Is also used to specIfy the order In whIch the
fIles are to be loaded. %he loadonstartup element Is wrItten In the deployment descrIptor as
follows:
servlet
servletnameServletNameservletname
servletclassClassNameservletclass
loa/onstartup1loa/onstartup
servlet
Note. The container loads the servlets in the order specified in the load-on-startup~
element.

30.What Is sessIon!
A sessIon refers to all the requests that a sIngle clIent mIght make to a server In the course of vIewIng
any pages assocIated wIth a gIven applIcatIon. SessIons are specIfIc to both the IndIvIdual user and the
applIcatIon. As a result, every user of an applIcatIon has a separate sessIon and has access to a
separate set of sessIon varIables.

31.What Is SessIon TrackIng!


SessIon trackIng Is a mechanIsm that servlets use to maIntaIn state about a serIes of requests from the
same user (that Is, requests orIgInatIng from the same browser) across some perIod of tIme.

32.What Is the need of SessIon TrackIng In web appIIcatIon!


H%%! Is a stateless protocol I.e., every request Is treated as new request. or web applIcatIons to be
more realIstIc they have to retaIn InformatIon across multIple requests. Such InformatIon whIch Is part
of the applIcatIon Is reffered as state. %o keep track of thIs state we need sessIon trackIng.

Typccl excmple: !uttIng thIngs one at a tIme Into a shoppIng cart, then checkIng outeach page
request must somehow be assocIated wIth prevIous requests.

33.What are the types of SessIon TrackIng !


SessIons need to work wIth all web browsers and take Into account the users securIty preferences.
%herefore there are a varIety of ways to send and receIve the IdentIfIer:
O UPL rewrItIng : UF rewrItIng Is a method of sessIon trackIng In whIch some extra data (sessIon
) Is appended at the end of each UF. %hIs extra data IdentIfIes the sessIon. %he server can
assocIate thIs sessIon IdentIfIer wIth the data It has stored about that sessIon. %hIs method Is
used wIth browsers that do not support cookIes or where the user has dIsabled the cookIes.

O HIdden Form FIeIds : SImIlar to UF rewrItIng. %he server embeds new hIdden fIelds In every
dynamIcally generated form page for the clIent. When the clIent submIts the form to the server
the hIdden fIelds IdentIfy the clIent.

O CookIes : CookIe Is a small amount of InformatIon sent by a servlet to a Web browser. Saved by
the browser, and later sent back to the server In subsequent requests. A cookIe has a name, a
sIngle value, and optIonal attrIbutes. A cookIe's value can unIquely IdentIfy a clIent.

O Secure Socket Layer (SSL) SessIons : Web browsers that support Secure Socket ayer
communIcatIon can use SS's support vIa H%%!S for generatIng a unIque sessIon key as part of
the encrypted conversatIon.

Learn more about Session Tracking

34.How do I use cookIes to store sessIon state on the cIIent!


n a servlet, the HttpServletFesponse and HttpServletFequest objects passed to method
HttpServlet.servIce() can be used to create cookIes on the clIent and use cookIe InformatIon
transmItted durIng clIent requests. JS!s can also use cookIes, In scrIptlet code or, preferably, from
wIthIn custom tag code.
O %o set a cookIe on the clIent, use the addCookIe() method In class HttpServletFesponse.
ultIple cookIes may be set for the same request, and a sIngle cookIe name may have multIple
values.
O %o get all of the cookIes assocIated wIth a sIngle H%%! request, use the getCookIes() method of
class HttpServletFequest

35.What are some advantages of storIng sessIon state In cookIes!


O CookIes are usually persIstent, so for lowsecurIty sItes, user data that needs to be stored long
term (such as a user , hIstorIcal InformatIon, etc.) can be maIntaIned easIly wIth no server
InteractIon.
O or small and medIumsIzed sessIon data, the entIre sessIon data (Instead of just the sessIon
) can be kept In the cookIe.

36.What are some dIsadvantages of storIng


sessIon state In cookIes!
O CookIes are controlled by
programmIng a lowlevel A!, whIch
Is more dIffIcult to Implement than
some other approaches.
O All data for a sessIon are kept on
the clIent. CorruptIon, expIratIon or
purgIng of cookIe fIles can all result
In Incomplete, InconsIstent, or
mIssIng InformatIon.
O CookIes may not be avaIlable for many reasons: the user may have dIsabled them, the browser
versIon may not support them, the browser may be behInd a fIrewall that fIlters cookIes, and
so on. Servlets and JS! pages that rely exclusIvely on cookIes for clIentsIde sessIon state wIll
not operate properly for all clIents. UsIng cookIes, and then swItchIng to an alternate clIent
sIde sessIon state strategy In cases where cookIes aren't avaIlable, complIcates development
and maIntenance.
O 8rowser Instances share cookIes, so users cannot have multIple sImultaneous sessIons.
O CookIebased solutIons work only for H%%! clIents. %hIs Is because cookIes are a feature of the
H%%! protocol. NotIce that the whIle package javax.servlet.http supports sessIon
management (vIa classHttpSession), package javax.servlet has no such support.
!eople who read this, also read:-
SprIng IntervIew uestIons
WebservIces uestIons
2EE CertIfIcatIon
IatIs an aIternatIve to HIbernate
TIbco IntervIew uestIons

37.What Is UPL rewrItIng!


UF rewrItIng Is a method of sessIon trackIng In whIch some extra data Is appended at the end of each
UF. %hIs extra data IdentIfIes the sessIon. %he server can assocIate thIs sessIon IdentIfIer wIth the
data It has stored about that sessIon.
Every UF on the page must be encoded usIng method HttpServlet#esponse.encodeUF(). Each tIme
a UF Is output, the servlet passes the UF to encodeUF(), whIch encodes sessIon In the UF If the
browser Isn't acceptIng cookIes, or If the sessIon trackIng Is turned off.
E.g., http://abc/path/Index.jsp;jsessIonId=2J465hfhs
Advantages
O UF rewrItIng works just about everywhere, especIally when cookIes are turned off.
O ultIple sImultaneous sessIons are possIble for a sIngle user. SessIon InformatIon Is local to
each browser Instance, sInce It's stored In UFs In each page beIng dIsplayed. %hIs scheme Isn't
foolproof, though, sInce users can start a new browser Instance usIng a UF for an actIve
sessIon, and confuse the server by InteractIng wIth the same sessIon through two Instances.
O EntIrely statIc pages cannot be used wIth UF rewrItIng, sInce every lInk must be dynamIcally
wrItten wIth the sessIon state. t Is possIble to combIne statIc and dynamIc content, usIng (for
example) templatIng or serversIde Includes. %hIs lImItatIon Is also a barrIer to IntegratIng
legacy web pages wIth newer, servletbased pages.

0IsAdvantages
O Every UF on a page whIch needs the sessIon InformatIon must be rewrItten each tIme a page Is
served. Not only Is thIs expensIve computatIonally, but It can greatly Increase communIcatIon
overhead.
O UF rewrItIng lImIts the clIent's InteractIon wIth the server to H%%! CE%s, whIch can result In
awkward restrIctIons on the page.
O UF rewrItIng does not work well wIth JS! technology.
O f a clIent workstatIon crashes, all of the UFs (and therefore all of the data for that sessIon)
are lost.

38.How can an exIstIng sessIon be InvaIIdated!


An exIstIng sessIon can be InvalIdated In the followIng two ways:
O SettIng tImeout In the deployment descrIptor: %hIs can be done by specIfyIng tImeout between
the sessiontimeouttags as follows:
sessioncon1i
session-timeout>10</session-timeout>
sessioncon1i
%hIs wIll set the tIme for sessIon tImeout to be ten mInutes.

O SettIng tImeout programmatIcally: %hIs wIll set the tImeout for a specIfIc sessIon. %he syntax
for settIng the tImeout programmatIcally Is as follows:
publicvoi/setMaxInactiveInterval(intinterval)
%he setMaxInactiveInterval() method sets the maxImum tIme In seconds before a sessIon
becomes InvalId.
Note :SettIng the InactIve perIod as neyctve(1), mckes the contcner stop trcckny sesson,
.e, sesson never expres.

3.How can the sessIon In ServIet can be destroyed!


An exIstIng sessIon can be destroyed In the followIng two ways:
O !rogramatIcally : UsIng session.invali/ate() method, whIch makes the contaIner abonden
the sessIon on whIch the method Is called.
O When the server Itself Is shutdown.

40.A cIIent sends requests to two dIfferent web components. oth of the components access the
sessIon. WIII they end up usIng the same sessIon object or dIfferent sessIon !
Creates only one sessIon I.e., they end up wIth usIng same sessIon .
SessIons Is specIfIc to the clIent but not the web components. And there Is a mappIng between
clIent and a sessIon.

41.What Is servIet Iazy IoadIng!


O A contaIner doesnot InItIalIze the servlets ass soon as It starts up, It InItIalIzes a servlet when It
receIves a request for that servlet fIrst tIme. %hIs Is called lazy loadIng.
O %he servlet specIfIcatIon defInes the loadonstartup element, whIch can be specIfIed In the
deployment descrIptor to make the servlet contaIner load and InItIalIze the servlet as soon as It
starts up.
O %he process of loadIng a servlet before any request comes In Is called preloadIng or
preInItIalIzIng a servlet.

42.What Is ServIet ChaInIng!


Servlet ChaInIng Is a method where the output of one servlet Is pIped Into a second servlet. %he output
of the second servlet could be pIped Into a thIrd servlet, and so on. %he last servlet In the chaIn
returns the output to the Web browser.

43.How are fIIters!


Ilters are Java components that are used to Intercept an IncomIng request to a Web resource and a
response sent back from the resource. t Is used to abstract any useful InformatIon contaIned In the
request or response. Some of the Important functIons performed by fIlters are as follows:
O SecurIty checks
O odIfyIng the request or response
O ata compressIon
O oggIng and audItIng
O Fesponse compressIon
Ilters are confIgured In the deployment descrIptor of a Web applIcatIon. Hence, a user Is not requIred
to recompIle anythIng to change the Input or output of the Web applIcatIon.

44.What are the functIons of an InterceptIng fIIter!


%he functIons of an InterceptIng fIlter are as follows:
O t Intercepts the request from a clIent before It reaches the servlet and modIfIes the request If
requIred.
O t Intercepts the response from the servlet back to the clIent and modIfIes the request If
requIred.
O %here can be many fIlters formIng a chaIn, In whIch case the output of one fIlter becomes an
Input to the next fIlter. Hence, varIous modIfIcatIons can be performed on a sIngle request and
response.

45.What are the functIons of the ServIet contaIner!


%he functIons of the Servlet contaIner are as follows:
O LIfecycIe management : t manages the lIfe and death of a servlet, such as class loadIng,
InstantIatIon, InItIalIzatIon, servIce, and makIng servlet Instances elIgIble for garbage
collectIon.
O CommunIcatIon support : t handles the communIcatIon between the servlet and the Web
server.
O huItIthreadIng support : t automatIcally creates a new thread for every servlet request
receIved. When the Servlet servIce() method completes, the thread dIes.
O 0ecIaratIve securIty : t manages the securIty InsIde the X deployment descrIptor fIle.
O SP support : %he contaIner Is responsIble for convertIng JS!s to servlets and for maIntaInIng
them.

You might also like