SlideShare a Scribd company logo
1. Explain about servlet lifecycle methods and their
syntaxes with the help of a diagram?
Servlets are managed components. They are managed by web container. Of the various
responsibilities of web container, servlet life cycle management is the most important
one. A servlet is managed through a well defined life cycle that defines how it is loaded,
instantiated ad initialized, handles requests from clients and how it is taken out of service.
The servlet life cycle methods are defined in the javax.servlet.Servlet interface of the
Servlet API that all Servlets must implement directly or indirectly by extending
GenericServlet or HttpServlet abstract classes. Most of the servlet you develop will
implement it by extending HttpServlet class.
  Init and Destroy:
Just like applets, servlets can define init() and destroy() methods. A servlet's init(ServletConfig)
method is called by the server immediately after the server constructs the servlet's instance.
Depending on the server and its configuration, this can be at any of these times:

     When the server starts

     When the servlet is first requested, just before the service() method is invoked

     At the request of the server administrator

  In any case, init() is guaranteed to be called before the servlet handles its first request.

The servlet life cycle methods defined in Servlet interface are init(), service() and
destroy(). The life cycle starts when container instantiates the object of servlet class and
calls the init() method, and ends with the container calling the destroy() method.
The syntaxes of this methods are shown below.
1)public void init(ServletConfig config) throws ServletException
  or
 public void init()
2)public void service(HttpServletRequest req, HttpServletResponse res) throws ServletException,
IOException

3)public void destroy()



The servlet life cycle consists of four steps, instantiation, initialization, request handling
and end of service.

Loading and instantiation
During this step, web container loads the servlet class and creates a new instance of the
servlet. The container can create a servlet instance at container startup or it can delay it
until the servlet is needed to service a request.

Initialization
During initialization stage of the Servlet life cycle, the web container initializes the
servlet instance by calling the init() method. The container passes an object implementing
the ServletConfig interface via the init() method. This configuration object allows the
servlet to access name-value initialization parameters from the web application

Request handling service() method
After a servlet is properly initialized, the servlet container may use it to handle client
requests. Requests are represented by request objects of type ServletRequest. The servlet
fills out response to requests by calling methods of a provided object of type
ServletResponse. These objects are passed as parameters to the service method of the
Servlet interface. In the case of an HTTP request, the objects provided by the container
are of types HttpServletRequest and HttpServletResponse.

End of service destroy() method
When servlet container determines that the servlet should be removed from the service, it
calls the destroy() method of the servlet to allow servlet to release any resources it is
using (eg. database connections or file handles). Before calling the destroy() method, the
container allows any request threads that are currently running in the service method to
complete execution within a defined time limit. Once the servlet is removed out of
service, container will not send any requests to the servlet. If the servlet needs to be put in
service again, the container will create a new servlet instance and the life cycle begins
from the initialization phase.
lifecycle of a servlet



Example:
import java.io.*;

    import javax.servlet.*;

    import javax.servlet.http.*;



    public class InitCounter extends HttpServlet

{

    int count;

     public void init(ServletConfig config) throws ServletException {

         super.init(config);

         String initial = config.getInitParameter("initial");

         try {

             count = Integer.parseInt(initial);

         }

         catch (NumberFormatException e) {

             count = 0;

         }

     }

             public void doGet(HttpServletRequest req, HttpServletResponse res)

                          throws ServletException, IOException {

                 res.setContentType("text/plain");

                PrintWriter out = res.getWriter();

               count++;

         out.println("Since loading (and with a possible initialization");
out.println("parameter figured in), this servlet has been accessed");

          out.println(count + " times.");

      }

  }



   The init() method accepts an object that implements the ServletConfig interface. It uses the
config object's getInitParameter() method to get the value for the init parameter named initial.
This method takes the name of the parameter as a String and returns the value as a String. There
is no way to get the value as any other type. This servlet therefore converts the String value to an
int or, if there's a problem, defaults to a value of 0.

More Related Content

PDF
Servlet and servlet life cycle
PPT
Servlet life cycle
DOCX
Servlet
PPTX
Chapter 3 servlet & jsp
PPT
Java servlets
PPT
Servlet ppt by vikas jagtap
PPT
JAVA Servlets
PPT
Servlet and servlet life cycle
Servlet life cycle
Servlet
Chapter 3 servlet & jsp
Java servlets
Servlet ppt by vikas jagtap
JAVA Servlets

What's hot (20)

PPTX
Javax.servlet,http packages
PPTX
Servlets
PPT
Java servlet life cycle - methods ppt
PPTX
Java Servlets
PPT
An Introduction To Java Web Technology
PPT
Java Servlet
PPTX
PPTX
Java Servlets
PPTX
Servlet api & servlet http package
PDF
java servlet and servlet programming
PPTX
PPT
Java - Servlet - Mazenet Solution
PPTX
Servlets
PPTX
Servletarchitecture,lifecycle,get,post
PPT
Servlet/JSP course chapter 1: Introduction to servlets
PPT
Knowledge Sharing : Java Servlet
PPTX
java Servlet technology
PDF
Java servlets
PPT
Java Servlets
DOC
Java Servlets & JSP
Javax.servlet,http packages
Servlets
Java servlet life cycle - methods ppt
Java Servlets
An Introduction To Java Web Technology
Java Servlet
Java Servlets
Servlet api & servlet http package
java servlet and servlet programming
Java - Servlet - Mazenet Solution
Servlets
Servletarchitecture,lifecycle,get,post
Servlet/JSP course chapter 1: Introduction to servlets
Knowledge Sharing : Java Servlet
java Servlet technology
Java servlets
Java Servlets
Java Servlets & JSP
Ad

Similar to Servlet lifecycle (20)

PPTX
Servlet and Servlet Life Cycle
PPTX
Servlet session 2
PPTX
Servlets
PPT
Servlet lifecycle
PDF
Servletand sessiontracking
PPT
S E R V L E T S
PPTX
Enterprise java unit-1_chapter-3
PPTX
J servlets
PPTX
LIFE CYCLE OF SERVLET
PPTX
JAVA SERVLETS acts as a middle layer between a request coming from a web brow...
PPTX
Introduction to Servlet.pptx
PPTX
ajava unit 1.pptx
PPTX
SevletLifeCycle
PPTX
SERVLET in web technolgy engineering.pptx
PDF
Servlet Life Cycle & Generic Servlet
PPTX
java Servlet_Life_Cycle_Notes with basic level
PPTX
Servlet_Life_cycle has details about the phases.pptx
PDF
servlet_lifecycle.pdf
PPTX
21CS642 Module 4_1 Servlets PPT.pptx VI SEM CSE Students
PPTX
Java servlets
Servlet and Servlet Life Cycle
Servlet session 2
Servlets
Servlet lifecycle
Servletand sessiontracking
S E R V L E T S
Enterprise java unit-1_chapter-3
J servlets
LIFE CYCLE OF SERVLET
JAVA SERVLETS acts as a middle layer between a request coming from a web brow...
Introduction to Servlet.pptx
ajava unit 1.pptx
SevletLifeCycle
SERVLET in web technolgy engineering.pptx
Servlet Life Cycle & Generic Servlet
java Servlet_Life_Cycle_Notes with basic level
Servlet_Life_cycle has details about the phases.pptx
servlet_lifecycle.pdf
21CS642 Module 4_1 Servlets PPT.pptx VI SEM CSE Students
Java servlets
Ad

Recently uploaded (20)

PPTX
202450812 BayCHI UCSC-SV 20250812 v17.pptx
PDF
STATICS OF THE RIGID BODIES Hibbelers.pdf
PDF
Yogi Goddess Pres Conference Studio Updates
PPTX
Pharmacology of Heart Failure /Pharmacotherapy of CHF
PDF
RTP_AR_KS1_Tutor's Guide_English [FOR REPRODUCTION].pdf
PPTX
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
PPTX
Pharma ospi slides which help in ospi learning
PDF
O5-L3 Freight Transport Ops (International) V1.pdf
PPTX
Cell Structure & Organelles in detailed.
PDF
OBE - B.A.(HON'S) IN INTERIOR ARCHITECTURE -Ar.MOHIUDDIN.pdf
PPTX
master seminar digital applications in india
PDF
Trump Administration's workforce development strategy
PDF
01-Introduction-to-Information-Management.pdf
PPTX
GDM (1) (1).pptx small presentation for students
PDF
grade 11-chemistry_fetena_net_5883.pdf teacher guide for all student
PPTX
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
PPTX
Orientation - ARALprogram of Deped to the Parents.pptx
PPTX
Microbial diseases, their pathogenesis and prophylaxis
PDF
O7-L3 Supply Chain Operations - ICLT Program
PPTX
Cell Types and Its function , kingdom of life
202450812 BayCHI UCSC-SV 20250812 v17.pptx
STATICS OF THE RIGID BODIES Hibbelers.pdf
Yogi Goddess Pres Conference Studio Updates
Pharmacology of Heart Failure /Pharmacotherapy of CHF
RTP_AR_KS1_Tutor's Guide_English [FOR REPRODUCTION].pdf
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
Pharma ospi slides which help in ospi learning
O5-L3 Freight Transport Ops (International) V1.pdf
Cell Structure & Organelles in detailed.
OBE - B.A.(HON'S) IN INTERIOR ARCHITECTURE -Ar.MOHIUDDIN.pdf
master seminar digital applications in india
Trump Administration's workforce development strategy
01-Introduction-to-Information-Management.pdf
GDM (1) (1).pptx small presentation for students
grade 11-chemistry_fetena_net_5883.pdf teacher guide for all student
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
Orientation - ARALprogram of Deped to the Parents.pptx
Microbial diseases, their pathogenesis and prophylaxis
O7-L3 Supply Chain Operations - ICLT Program
Cell Types and Its function , kingdom of life

Servlet lifecycle

  • 1. 1. Explain about servlet lifecycle methods and their syntaxes with the help of a diagram? Servlets are managed components. They are managed by web container. Of the various responsibilities of web container, servlet life cycle management is the most important one. A servlet is managed through a well defined life cycle that defines how it is loaded, instantiated ad initialized, handles requests from clients and how it is taken out of service. The servlet life cycle methods are defined in the javax.servlet.Servlet interface of the Servlet API that all Servlets must implement directly or indirectly by extending GenericServlet or HttpServlet abstract classes. Most of the servlet you develop will implement it by extending HttpServlet class. Init and Destroy: Just like applets, servlets can define init() and destroy() methods. A servlet's init(ServletConfig) method is called by the server immediately after the server constructs the servlet's instance. Depending on the server and its configuration, this can be at any of these times: When the server starts When the servlet is first requested, just before the service() method is invoked At the request of the server administrator In any case, init() is guaranteed to be called before the servlet handles its first request. The servlet life cycle methods defined in Servlet interface are init(), service() and destroy(). The life cycle starts when container instantiates the object of servlet class and calls the init() method, and ends with the container calling the destroy() method. The syntaxes of this methods are shown below. 1)public void init(ServletConfig config) throws ServletException or public void init() 2)public void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException 3)public void destroy() The servlet life cycle consists of four steps, instantiation, initialization, request handling and end of service. Loading and instantiation During this step, web container loads the servlet class and creates a new instance of the servlet. The container can create a servlet instance at container startup or it can delay it
  • 2. until the servlet is needed to service a request. Initialization During initialization stage of the Servlet life cycle, the web container initializes the servlet instance by calling the init() method. The container passes an object implementing the ServletConfig interface via the init() method. This configuration object allows the servlet to access name-value initialization parameters from the web application Request handling service() method After a servlet is properly initialized, the servlet container may use it to handle client requests. Requests are represented by request objects of type ServletRequest. The servlet fills out response to requests by calling methods of a provided object of type ServletResponse. These objects are passed as parameters to the service method of the Servlet interface. In the case of an HTTP request, the objects provided by the container are of types HttpServletRequest and HttpServletResponse. End of service destroy() method When servlet container determines that the servlet should be removed from the service, it calls the destroy() method of the servlet to allow servlet to release any resources it is using (eg. database connections or file handles). Before calling the destroy() method, the container allows any request threads that are currently running in the service method to complete execution within a defined time limit. Once the servlet is removed out of service, container will not send any requests to the servlet. If the servlet needs to be put in service again, the container will create a new servlet instance and the life cycle begins from the initialization phase.
  • 3. lifecycle of a servlet Example: import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class InitCounter extends HttpServlet { int count; public void init(ServletConfig config) throws ServletException { super.init(config); String initial = config.getInitParameter("initial"); try { count = Integer.parseInt(initial); } catch (NumberFormatException e) { count = 0; } } public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { res.setContentType("text/plain"); PrintWriter out = res.getWriter(); count++; out.println("Since loading (and with a possible initialization");
  • 4. out.println("parameter figured in), this servlet has been accessed"); out.println(count + " times."); } } The init() method accepts an object that implements the ServletConfig interface. It uses the config object's getInitParameter() method to get the value for the init parameter named initial. This method takes the name of the parameter as a String and returns the value as a String. There is no way to get the value as any other type. This servlet therefore converts the String value to an int or, if there's a problem, defaults to a value of 0.