Servlet life cycle

4,385 views 35 slides Oct 27, 2021
Slide 1
Slide 1 of 35
Slide 1
1
Slide 2
2
Slide 3
3
Slide 4
4
Slide 5
5
Slide 6
6
Slide 7
7
Slide 8
8
Slide 9
9
Slide 10
10
Slide 11
11
Slide 12
12
Slide 13
13
Slide 14
14
Slide 15
15
Slide 16
16
Slide 17
17
Slide 18
18
Slide 19
19
Slide 20
20
Slide 21
21
Slide 22
22
Slide 23
23
Slide 24
24
Slide 25
25
Slide 26
26
Slide 27
27
Slide 28
28
Slide 29
29
Slide 30
30
Slide 31
31
Slide 32
32
Slide 33
33
Slide 34
34
Slide 35
35

About This Presentation

Servlets


Slide Content

Servlet Life Cycle

Servlet Life Cycle
•Aservletlifecyclecanbedefinedastheentire
processfromitscreationtillthedestruction.
•Theservletisinitializedbycallingtheinit()
method.
•Theservletcallsservice()methodtoprocessa
client'srequest.
•Theservletisterminatedbycallingthe
destroy()method.
•Finally,servletisgarbagecollectedbythe
garbagecollectoroftheJVM.

Servletlifecyclecontainsfivesteps:
1.LoadingofServlet
2.CreatinginstanceofServlet
3.Invokeinit()once
4.Invokeservice()repeatedlyforeachclient
request
5.Invokedestroy()
3

Step1:LoadingofServlet
Whenthewebserver(e.g.ApacheTomcat)starts
up,theservletcontainerdeployandloadsallthe
servlets.
Step2:CreatinginstanceofServlet
OncealltheServletclassesloaded,theservlet
containercreatesinstancesofeachservletclass.
Servletcontainercreatesonlyonceinstanceper
servletclassandalltherequeststotheservletare
executedonthesameservletinstance.
Step3:Invokeinit()method
Oncealltheservletclassesareinstantiated,the
init()methodisinvokedforeachinstantiated
servlet.
4

Step 4: Invoke service() method
Eachtimethewebserverreceivesarequestforservlet,
itspawnsanewthreadthatcallsservice()method.
IftheservletisGenericServletthentherequestis
servedbytheservice()methoditself,
iftheservletisHttpServletthenservice()method
receivestherequestanddispatchesittothecorrect
handlermethodbasedonthetypeofrequest.
Step 5: Invoke destroy() method
Whenservletcontainershutsdown(thisusually
happenswhenwestopthewebserver),itunloadsall
theservletsandcallsdestroy()methodforeach
initializedservlets. 5

Architecture Diagram:
Thefollowingfiguredepictsatypicalservletlife-cycle
scenario.
FirsttheHTTPrequestscomingtotheserver
aredelegatedtotheservletcontainer.
Theservletcontainerloadstheservletbefore
invokingtheservice()method.
Thentheservletcontainerhandlesmultiple
requestsbyspawningmultiplethreads,each
threadexecutingtheservice()methodofa
singleinstanceoftheservlet.
6

7

Servlet life cycle

How Servlet Works?
1)Whenthewebserver(e.g.ApacheTomcat)startsup,
theservletcontainerdeployandloadsalltheservlets.
2)Oncetheservletisloaded,theservletcontainer
createstheinstanceofservletclass.Foreach
instantiatedservlet,itsinit()methodisinvoked.
3)Client(userbrowser)sendsanHttprequesttoweb
serveronacertainport.Eachtimethewebserver
receivesarequest,theservletcontainercreates
HttpServletRequestandHttpServletResponseobjects.
TheHttpServletRequestobjectprovidestheaccessto
therequestinformationandtheHttpServletResponse
objectallowsustoformatandchangethehttp
responsebeforesendingittotheclient.
9

The init() method :
•Theinit()methodisdesignedtobecalledonly
once.
•Itiscalledwhentheservletisfirstcreated,
andnotcalledagainforeachuserrequest.
•So,itisusedforone-timeinitializations,just
aswiththeinit()methodofapplets.
•Theservletisnormallycreatedwhenauser
firstinvokesaURLcorrespondingtothe
servlet.

The init() method
public void init() throws ServletException
{
// Initialization code...
}

The service() method :
•Theservice()methodisthemainmethod
toperformtheactualtask.
•Theservletcontainer(i.e.webserver)
callstheservice()methodtohandle
requestscomingfromtheclient(
browsers)andtowritetheformatted
responsebacktotheclient.

•Eachtimeiftheserverreceivesarequestfora
servlet,theserverissuesanewthreadand
callsservice.
•Theservice()methodcheckstheHTTPrequest
type(GET,POST,PUT,DELETE,etc.)andcalls
doGet,doPost,doPut,doDelete,etc.methods
asappropriate.

signature of service()
publicvoidservice(ServletRequestrequest,
ServletResponse response) throws
ServletException,IOException
{
}

•Theservice()methodiscalledbythe
containerandservicemethodinvokesdoGet,
doPost,doPut,doDelete,etc.methodsas
appropriate.
•Soyouhavenothingtodowithservice()
methodbutyouoverrideeitherdoGet()or
doPost()dependingonwhattypeofrequest
youreceivefromtheclient.
•ThedoGet()anddoPost()aremostfrequently
usedmethodswithineachservicerequest.

signature of the doGet() method
public void doGet(HttpServletRequest
request, HttpServletResponseresponse)
throws ServletException, IOException
{
// Servlet code
}

signature of the doPost() method
publicvoiddoPost(HttpServletRequestrequest,
HttpServletResponseresponse) throws
ServletException,IOException
{
//Servletcode
}

The destroy() method :
•Thedestroy()methodiscalledonlyonceatthe
endofthelifecycleofaservlet.
•Thismethodgivesyourservletachancetoclose
databaseconnections,haltbackgroundthreads,
writecookielistsorhitcountstodisk,and
performothersuchcleanupactivities.
•Afterthedestroy()methodiscalled,theservlet
objectismarkedforgarbagecollection.The
destroymethoddefinitionlookslikethis:
•publicvoiddestroy(){//Finalizationcode...}

NetBeans IDE

Select new project from File menu

Select Java Web

Select Web Application and Click Next

Give the Application Name and click next

Server Settings & Click Finish button

The basic terminology used in servlet
•HTTP
•HTTP Request Types
•Difference between Get and Post method
•Container
•Server and Difference between web server
and application server
•Content Type
•Introduction of XML
•Deployment

HTTP (Hyper Text Transfer Protocol)
•Http is the protocol that allows web servers
and browsers to exchange data over the web.
•It is a request response protocol.
•Http uses reliable TCP connections by default
on TCP port 80.
•Itisstatelessmeanseachrequestis
consideredasthenewrequest.Inother
words,serverdoesn'trecognizetheuserby
default.

HTTP

Http Request Methods
•Everyrequesthasaheaderthattellsthestatusoftheclient.
•Therearemanyrequestmethods.GetandPostrequestsare
mostlyused.
•The http request methods are:
•GET
•POST
•HEAD
•PUT
•DELETE
•OPTIONS
•TRACE

HTTP Request Description
GET Asks to get the resource at the requested URL.
POST
Asks the server to accept the body info attached. It is
like GET request with extra info sent with the request.
HEAD
Asks for only the header part of whatever a GET would
return. Just like GET but with no body.
TRACE
Asks for the loopback of the request message, for
testing or troubleshooting.
PUT
Says to put the enclosed info (the body) at the
requested URL.
DELETE Says to delete the resource at the requested URL.
OPTIONS
Asks for a list of the HTTP methods to which the thing
at the request URL can respond

What is the difference between Get and Post?
GET POST
1) In case of Get request, only limited
amount of data can be sent because
data is sent in header.
In case of post request, large amount
of data can be sent because data is
sent in body.
2) Get request is not secured because
data is exposed in URL bar.
Post request is secured because data is
not exposed in URL bar.
3) Get request can be bookmarkedPost request cannot be bookmarked
4) Get request is idempotent. It means
second request will be ignored until
response of first request is delivered.
Post request is non-idempotent
5) Get request is more efficient and
used more than Post
Post request is less efficient and used
less than get.

Container
•It provides runtime environment for Java Web
or JavaEE (J2EE) applications.
•It performs many operations that are given
below:
•Life Cycle Management
•Multithreaded support
•Object Pooling
•Security etc.

Server
•It is a running program or software that
provides services.
•There are two types of servers:
•Web Server
•Application Server

•Web Server
•Web server contains only web or servlet container. It can be
used for servlet, jsp, struts, jsf etc. It can't be used for EJB.
•Example of Web Servers are: Apache Tomcatand Resin.
•Application Server
•Application server contains Web and EJB containers. It can be
used for servlet, jsp, struts, jsf, ejb etc.
•Example of Application Servers are:
•JBossOpen-source server from JBoss community.
•Glassfishprovided by Sun Microsystem. Now acquired by
Oracle.
•Weblogicprovided by Oracle. It more secured.
•Websphereprovided by IBM.

Content Type
•ContentTypeisalsoknownasMIME(MultipurposeinternetMail
Extension)Type.ItisaHTTPheaderthatprovidesthedescriptionabout
whatareyousendingtothebrowser.
•There are many content types:
•text/html
•text/plain
•application/msword
•application/vnd.ms-excel
•application/jar
•application/pdf
•application/octet-stream
•application/x-zip
•images/jpeg
•video/quicktime etc.
Tags