SlideShare a Scribd company logo
1 of 35
Servlet Life Cycle
Servlet Life Cycle
• A servlet life cycle can be defined as the entire
process from its creation till the destruction.
• The servlet is initialized by calling the init()
method.
• The servlet calls service() method to process a
client's request.
• The servlet is terminated by calling the
destroy() method.
• Finally, servlet is garbage collected by the
garbage collector of the JVM.
Servlet life cycle contains five steps:
1. Loading of Servlet
2. Creating instance of Servlet
3. Invoke init() once
4. Invoke service() repeatedly for each client
request
5. Invoke destroy()
3
Step 1: Loading of Servlet
When the web server (e.g. Apache Tomcat) starts
up, the servlet container deploy and loads all the
servlets.
Step 2: Creating instance of Servlet
Once all the Servlet classes loaded, the servlet
container creates instances of each servlet class.
Servlet container creates only once instance per
servlet class and all the requests to the servlet are
executed on the same servlet instance.
Step 3: Invoke init() method
Once all the servlet classes are instantiated, the
init() method is invoked for each instantiated
servlet. 4
Step 4: Invoke service() method
Each time the web server receives a request for servlet,
it spawns a new thread that calls service() method.
If the servlet is GenericServlet then the request is
served by the service() method itself,
if the servlet is HttpServlet then service() method
receives the request and dispatches it to the correct
handler method based on the type of request.
Step 5: Invoke destroy() method
When servlet container shuts down(this usually
happens when we stop the web server), it unloads all
the servlets and calls destroy() method for each
initialized servlets. 5
Architecture Diagram:
The following figure depicts a typical servlet life-cycle
scenario.
First the HTTP requests coming to the server
are delegated to the servlet container.
The servlet container loads the servlet before
invoking the service() method.
Then the servlet container handles multiple
requests by spawning multiple threads, each
thread executing the service() method of a
single instance of the servlet.
6
7
Servlet life cycle
How Servlet Works?
1) When the web server (e.g. Apache Tomcat) starts up,
the servlet container deploy and loads all the servlets.
2) Once the servlet is loaded, the servlet container
creates the instance of servlet class. For each
instantiated servlet, its init() method is invoked.
3) Client (user browser) sends an Http request to web
server on a certain port. Each time the web server
receives a request, the servlet container creates
HttpServletRequest and HttpServletResponse objects.
The HttpServletRequest object provides the access to
the request information and the HttpServletResponse
object allows us to format and change the http
response before sending it to the client. 9
The init() method :
• The init() method is designed to be called only
once.
• It is called when the servlet is first created,
and not called again for each user request.
• So, it is used for one-time initializations, just
as with the init() method of applets.
• The servlet is normally created when a user
first invokes a URL corresponding to the
servlet.
The init() method
public void init() throws ServletException
{
// Initialization code...
}
The service() method :
• The service() method is the main method
to perform the actual task.
• The servlet container (i.e. web server)
calls the service() method to handle
requests coming from the client(
browsers) and to write the formatted
response back to the client.
• Each time if the server receives a request for a
servlet, the server issues a new thread and
calls service.
• The service() method checks the HTTP request
type (GET, POST, PUT, DELETE, etc.) and calls
doGet, doPost, doPut, doDelete, etc. methods
as appropriate.
signature of service()
public void service(ServletRequest request,
ServletResponse response) throws
ServletException, IOException
{
}
• The service() method is called by the
container and service method invokes doGet,
doPost, doPut, doDelete, etc. methods as
appropriate.
• So you have nothing to do with service()
method but you override either doGet() or
doPost() depending on what type of request
you receive from the client.
• The doGet() and doPost() are most frequently
used methods with in each service request.
signature of the doGet() method
public void doGet(HttpServletRequest
request, HttpServletResponse response)
throws ServletException, IOException
{
// Servlet code
}
signature of the doPost() method
public void doPost(HttpServletRequest request,
HttpServletResponse response) throws
ServletException, IOException
{
// Servlet code
}
The destroy() method :
• The destroy() method is called only once at the
end of the life cycle of a servlet.
• This method gives your servlet a chance to close
database connections, halt background threads,
write cookie lists or hit counts to disk, and
perform other such cleanup activities.
• After the destroy() method is called, the servlet
object is marked for garbage collection. The
destroy method definition looks like this:
• public void destroy() { // Finalization code... }
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.
• It is stateless means each request is
considered as the new request. In other
words, server doesn't recognize the user by
default.
HTTP
Http Request Methods
• Every request has a header that tells the status of the client.
• There are many request methods. Get and Post requests are
mostly used.
• 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 bookmarked Post 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 Tomcat and 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:
• JBoss Open-source server from JBoss community.
• Glassfish provided by Sun Microsystem. Now acquired by
Oracle.
• Weblogic provided by Oracle. It more secured.
• Websphere provided by IBM.
Content Type
• Content Type is also known as MIME (Multipurpose internet Mail
Extension) Type. It is a HTTP header that provides the description about
what are you sending to the browser.
• 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.

More Related Content

What's hot (20)

Jsp ppt
Jsp pptJsp ppt
Jsp ppt
 
Network programming in java - PPT
Network programming in java - PPTNetwork programming in java - PPT
Network programming in java - PPT
 
Java Servlets
Java ServletsJava Servlets
Java Servlets
 
Java rmi
Java rmiJava rmi
Java rmi
 
JDBC: java DataBase connectivity
JDBC: java DataBase connectivityJDBC: java DataBase connectivity
JDBC: java DataBase connectivity
 
Servlets
ServletsServlets
Servlets
 
MULTI THREADING IN JAVA
MULTI THREADING IN JAVAMULTI THREADING IN JAVA
MULTI THREADING IN JAVA
 
Socket Programming
Socket ProgrammingSocket Programming
Socket Programming
 
Applet life cycle
Applet life cycleApplet life cycle
Applet life cycle
 
Networking in Java
Networking in JavaNetworking in Java
Networking in Java
 
Java Networking
Java NetworkingJava Networking
Java Networking
 
Chapter 3 servlet & jsp
Chapter 3 servlet & jspChapter 3 servlet & jsp
Chapter 3 servlet & jsp
 
Servlets
ServletsServlets
Servlets
 
Jdbc ppt
Jdbc pptJdbc ppt
Jdbc ppt
 
enterprise java bean
enterprise java beanenterprise java bean
enterprise java bean
 
Threads concept in java
Threads concept in javaThreads concept in java
Threads concept in java
 
RPC: Remote procedure call
RPC: Remote procedure callRPC: Remote procedure call
RPC: Remote procedure call
 
Java beans
Java beansJava beans
Java beans
 
Socket programming in Java (PPTX)
Socket programming in Java (PPTX)Socket programming in Java (PPTX)
Socket programming in Java (PPTX)
 
Java Beans
Java BeansJava Beans
Java Beans
 

Similar to Servlet life cycle

IP UNIT III PPT.pptx
 IP UNIT III PPT.pptx IP UNIT III PPT.pptx
IP UNIT III PPT.pptxssuser92282c
 
Enterprise java unit-1_chapter-3
Enterprise java unit-1_chapter-3Enterprise java unit-1_chapter-3
Enterprise java unit-1_chapter-3sandeep54552
 
Java Servlet Programming under Ubuntu Linux by Tushar B Kute
Java Servlet Programming under Ubuntu Linux by Tushar B KuteJava Servlet Programming under Ubuntu Linux by Tushar B Kute
Java Servlet Programming under Ubuntu Linux by Tushar B KuteTushar B Kute
 
Java Servlets.pdf
Java Servlets.pdfJava Servlets.pdf
Java Servlets.pdfArumugam90
 
Servlet.ppt
Servlet.pptServlet.ppt
Servlet.pptkstalin2
 
Web Technologies -- Servlets 4 unit slides
Web Technologies -- Servlets   4 unit slidesWeb Technologies -- Servlets   4 unit slides
Web Technologies -- Servlets 4 unit slidesSasidhar Kothuru
 
Servlet ppt by vikas jagtap
Servlet ppt by vikas jagtapServlet ppt by vikas jagtap
Servlet ppt by vikas jagtapVikas Jagtap
 
IT2255 Web Essentials - Unit V Servlets and Database Connectivity
IT2255 Web Essentials - Unit V Servlets and Database ConnectivityIT2255 Web Essentials - Unit V Servlets and Database Connectivity
IT2255 Web Essentials - Unit V Servlets and Database Connectivitypkaviya
 
Dynamic content generation
Dynamic content generationDynamic content generation
Dynamic content generationEleonora Ciceri
 
J2EE : Java servlet and its types, environment
J2EE : Java servlet and its types, environmentJ2EE : Java servlet and its types, environment
J2EE : Java servlet and its types, environmentjoearunraja2
 

Similar to Servlet life cycle (20)

IP UNIT III PPT.pptx
 IP UNIT III PPT.pptx IP UNIT III PPT.pptx
IP UNIT III PPT.pptx
 
Servlet session 2
Servlet   session 2Servlet   session 2
Servlet session 2
 
Enterprise java unit-1_chapter-3
Enterprise java unit-1_chapter-3Enterprise java unit-1_chapter-3
Enterprise java unit-1_chapter-3
 
Java Servlet Programming under Ubuntu Linux by Tushar B Kute
Java Servlet Programming under Ubuntu Linux by Tushar B KuteJava Servlet Programming under Ubuntu Linux by Tushar B Kute
Java Servlet Programming under Ubuntu Linux by Tushar B Kute
 
Servlets
ServletsServlets
Servlets
 
Java Servlets.pdf
Java Servlets.pdfJava Servlets.pdf
Java Servlets.pdf
 
Servlet.ppt
Servlet.pptServlet.ppt
Servlet.ppt
 
Servlet.ppt
Servlet.pptServlet.ppt
Servlet.ppt
 
Servlet1.ppt
Servlet1.pptServlet1.ppt
Servlet1.ppt
 
Web Technologies -- Servlets 4 unit slides
Web Technologies -- Servlets   4 unit slidesWeb Technologies -- Servlets   4 unit slides
Web Technologies -- Servlets 4 unit slides
 
Servlet ppt by vikas jagtap
Servlet ppt by vikas jagtapServlet ppt by vikas jagtap
Servlet ppt by vikas jagtap
 
ajava unit 1.pptx
ajava unit 1.pptxajava unit 1.pptx
ajava unit 1.pptx
 
JAVA Servlets
JAVA ServletsJAVA Servlets
JAVA Servlets
 
Servlets
ServletsServlets
Servlets
 
SERVIET
SERVIETSERVIET
SERVIET
 
Wt unit 3
Wt unit 3 Wt unit 3
Wt unit 3
 
IT2255 Web Essentials - Unit V Servlets and Database Connectivity
IT2255 Web Essentials - Unit V Servlets and Database ConnectivityIT2255 Web Essentials - Unit V Servlets and Database Connectivity
IT2255 Web Essentials - Unit V Servlets and Database Connectivity
 
Dynamic content generation
Dynamic content generationDynamic content generation
Dynamic content generation
 
J2EE : Java servlet and its types, environment
J2EE : Java servlet and its types, environmentJ2EE : Java servlet and its types, environment
J2EE : Java servlet and its types, environment
 
Servlet.pptx
Servlet.pptxServlet.pptx
Servlet.pptx
 

Recently uploaded

social pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajansocial pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajanpragatimahajan3
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactdawncurless
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationnomboosow
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxSayali Powar
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAssociation for Project Management
 
Student login on Anyboli platform.helpin
Student login on Anyboli platform.helpinStudent login on Anyboli platform.helpin
Student login on Anyboli platform.helpinRaunakKeshri1
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsTechSoup
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeThiyagu K
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdfSoniaTolstoy
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDThiyagu K
 
JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...
JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...
JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...anjaliyadav012327
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactPECB
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxheathfieldcps1
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfJayanti Pande
 
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...Sapna Thakur
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingTechSoup
 

Recently uploaded (20)

social pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajansocial pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajan
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
 
Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communication
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across Sectors
 
Student login on Anyboli platform.helpin
Student login on Anyboli platform.helpinStudent login on Anyboli platform.helpin
Student login on Anyboli platform.helpin
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SD
 
JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...
JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...
JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
 
Advance Mobile Application Development class 07
Advance Mobile Application Development class 07Advance Mobile Application Development class 07
Advance Mobile Application Development class 07
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdf
 
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 

Servlet life cycle

  • 2. Servlet Life Cycle • A servlet life cycle can be defined as the entire process from its creation till the destruction. • The servlet is initialized by calling the init() method. • The servlet calls service() method to process a client's request. • The servlet is terminated by calling the destroy() method. • Finally, servlet is garbage collected by the garbage collector of the JVM.
  • 3. Servlet life cycle contains five steps: 1. Loading of Servlet 2. Creating instance of Servlet 3. Invoke init() once 4. Invoke service() repeatedly for each client request 5. Invoke destroy() 3
  • 4. Step 1: Loading of Servlet When the web server (e.g. Apache Tomcat) starts up, the servlet container deploy and loads all the servlets. Step 2: Creating instance of Servlet Once all the Servlet classes loaded, the servlet container creates instances of each servlet class. Servlet container creates only once instance per servlet class and all the requests to the servlet are executed on the same servlet instance. Step 3: Invoke init() method Once all the servlet classes are instantiated, the init() method is invoked for each instantiated servlet. 4
  • 5. Step 4: Invoke service() method Each time the web server receives a request for servlet, it spawns a new thread that calls service() method. If the servlet is GenericServlet then the request is served by the service() method itself, if the servlet is HttpServlet then service() method receives the request and dispatches it to the correct handler method based on the type of request. Step 5: Invoke destroy() method When servlet container shuts down(this usually happens when we stop the web server), it unloads all the servlets and calls destroy() method for each initialized servlets. 5
  • 6. Architecture Diagram: The following figure depicts a typical servlet life-cycle scenario. First the HTTP requests coming to the server are delegated to the servlet container. The servlet container loads the servlet before invoking the service() method. Then the servlet container handles multiple requests by spawning multiple threads, each thread executing the service() method of a single instance of the servlet. 6
  • 7. 7
  • 9. How Servlet Works? 1) When the web server (e.g. Apache Tomcat) starts up, the servlet container deploy and loads all the servlets. 2) Once the servlet is loaded, the servlet container creates the instance of servlet class. For each instantiated servlet, its init() method is invoked. 3) Client (user browser) sends an Http request to web server on a certain port. Each time the web server receives a request, the servlet container creates HttpServletRequest and HttpServletResponse objects. The HttpServletRequest object provides the access to the request information and the HttpServletResponse object allows us to format and change the http response before sending it to the client. 9
  • 10. The init() method : • The init() method is designed to be called only once. • It is called when the servlet is first created, and not called again for each user request. • So, it is used for one-time initializations, just as with the init() method of applets. • The servlet is normally created when a user first invokes a URL corresponding to the servlet.
  • 11. The init() method public void init() throws ServletException { // Initialization code... }
  • 12. The service() method : • The service() method is the main method to perform the actual task. • The servlet container (i.e. web server) calls the service() method to handle requests coming from the client( browsers) and to write the formatted response back to the client.
  • 13. • Each time if the server receives a request for a servlet, the server issues a new thread and calls service. • The service() method checks the HTTP request type (GET, POST, PUT, DELETE, etc.) and calls doGet, doPost, doPut, doDelete, etc. methods as appropriate.
  • 14. signature of service() public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException { }
  • 15. • The service() method is called by the container and service method invokes doGet, doPost, doPut, doDelete, etc. methods as appropriate. • So you have nothing to do with service() method but you override either doGet() or doPost() depending on what type of request you receive from the client. • The doGet() and doPost() are most frequently used methods with in each service request.
  • 16. signature of the doGet() method public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Servlet code }
  • 17. signature of the doPost() method public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Servlet code }
  • 18. The destroy() method : • The destroy() method is called only once at the end of the life cycle of a servlet. • This method gives your servlet a chance to close database connections, halt background threads, write cookie lists or hit counts to disk, and perform other such cleanup activities. • After the destroy() method is called, the servlet object is marked for garbage collection. The destroy method definition looks like this: • public void destroy() { // Finalization code... }
  • 20. Select new project from File menu
  • 22. Select Web Application and Click Next
  • 23. Give the Application Name and click next
  • 24. Server Settings & Click Finish button
  • 25.
  • 26. 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
  • 27. 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. • It is stateless means each request is considered as the new request. In other words, server doesn't recognize the user by default.
  • 28. HTTP
  • 29. Http Request Methods • Every request has a header that tells the status of the client. • There are many request methods. Get and Post requests are mostly used. • The http request methods are: • GET • POST • HEAD • PUT • DELETE • OPTIONS • TRACE
  • 30. 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
  • 31. 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 bookmarked Post 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.
  • 32. 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.
  • 33. Server • It is a running program or software that provides services. • There are two types of servers: • Web Server • Application Server
  • 34. • 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 Tomcat and 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: • JBoss Open-source server from JBoss community. • Glassfish provided by Sun Microsystem. Now acquired by Oracle. • Weblogic provided by Oracle. It more secured. • Websphere provided by IBM.
  • 35. Content Type • Content Type is also known as MIME (Multipurpose internet Mail Extension) Type. It is a HTTP header that provides the description about what are you sending to the browser. • 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.