Call for New Batch / Any Query / Demo Classes : ☎ 08871209400 , 7987028543 , Zone-2,M.P.Nagar,Bhopal

Life cycle of a servlet

The lifecycle of a servlet is controlled by the container in which the servlet has been deployed. When a request is mapped to a servlet, the container performs the following steps.

1. If an instance of the servlet does not exist, the web container:

● Loads the servlet class
● Creates an instance of the servlet class

Initializes the servlet instance by calling the init method (initialization is covered in Creating and Initializing a Servlet)

2. The container invokes the service method, passing request and response objects. Service methods are discussed in Writing Service Methods.

If it needs to remove the servlet, the container finalizes the servlet by calling the servlet's destroy method. For more information, see Finalizing a Servlet.

Handling Servlet Lifecycle Events

You can monitor and react to events in a servlet's lifecycle by defining listener objects whose methods get invoked when lifecycle events occur. To use these listener objects, you must define and specify the listener class.

Defining the Listener Class

You define a listener class as an implementation of a listener interface. Table 15-1 lists the events that can be monitored and the corresponding interface that must be implemented. When a listener method is invoked, it is passed an event that contains information appropriate to the event.

ObjectEventListener Interface and Event Class
Web contextInitialization and destructionjavax.servlet.ServletContextListener and ServletContextEvent
Web contextAttribute added, removed, or replacedjavax.servlet.ServletContextAttributeListener and ServletContextAttributeEvent
SessionCreation, invalidation, activation, passivation, and timeoutjavax.servlet.http.HttpSessionListener, javax.servlet.http.HttpSessionActivationListener, and HttpSessionEvent
SessionAttribute added, removed, or replacedjavax.servlet.http.HttpSessionAttributeListener and HttpSessionBindingEvent
RequestA servlet request has started being processed by web componentsjavax.servlet.ServletRequestListener and ServletRequestEvent
RequestAttribute added, removed, or replacedjavax.servlet.ServletRequestAttributeListener and ServletRequestAttributeEvent

Three methods are central to the life cycle of a servlet. These are init(), service(), and destroy(). They are implemented by every servlet and are invoked at specific times by the server.

• During initialization stage of the servlet life cycle, the web container initializes the servlet instance by calling the init() method, passing an object implementing the javax.servlet.ServletConfig interface. This configuration object allows the servlet to access name-value initialization parameters from the web application.
• After initialization, the servlet instance can service client requests. Each request is serviced in its own separate thread. The web container calls the service() method of the servlet for every request.
• Finally, the web container calls the destroy() method that takes the servlet out of service. The destroy() method, like init(), is called only once in the lifecycle of a servlet.

The following example servlet prints how many times its service() method was called.
The service() method of HttpServlet class dispatches requests to the methods doGet(), doPost(), doPut(), doDelete(), and so on; according to the HTTP request. In the example below service() is overridden and does not distinguish which HTTP request method it serves.

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class ServletLifeCycleExample extends HttpServlet {
    private int count;
    public void init(final ServletConfig config) throws ServletException {
        getServletContext().log("init() called");
        count = 0;
    protected void service(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException {
        getServletContext().log("service() called");
        response.getWriter().write("Incrementing the count to " + count);
    public void destroy() {
        getServletContext().log("destroy() called");

References : oracle | wikipedia « Privious Post » « Next Post » share on :        :  

Love to hear your Views / Guidance / Recommendations on this Post…

Global Tech NewsTop Programing Index January 2018January Headline Programming Language C awarded Language of the Year 2017,language C appears to be the fastest grower of 2017 in the TIOBE index and thus is declared programming language of the yearProgramming languages used in most popular websitesThe most popular websites have in common that they are dynamic websites. Their development typically involves server side coding client side coding and database technologyTop 10 Computer Science Skills That Could Sharpen Non-Computer Science CareersWhat do design marketing, engineering and data analysis have in common Theyre all careers where employers increasingly demand computer science skills.Oracle Buys AconexCreates the Worlds Most Comprehensive Cloud Offering for Managing All Aspects of Construction ProjectsOracle Unveils Worlds First Autonomous Database CloudAlso Introduces Oracle Autonomous Data Warehouse Cloud that has Demonstrated Performance of 10x Faster at Half the Cost of AmazonRecent List and Rankings Of Top Programming LanguagesThe programming languages Kotlin and C seem to be the only candidates to become programming language of the year 2017. TIOBE will announce the winner of this award next monthProgramming Index for November 2017This index ranks programming languages on the basis of their popularity.October Rankings Of Top Programming LanguagesIn the Beginning of this year the Programming Language Swift Peaked at a Rating of 2.3% in the TIOBE index and Even Reached a top 10 position. But now it is back at Position 16 and Constantly Declining Month after Month. Until recently it was quite Common to Program Android apps in Java and iOS apps in Swift/Objective-CAutosizing TextViewsAndroid O and Support Lib 26 allow to the text size expand,for Best user Experience with Text, Material Design Recommends Using a Dynamic Type Instead of smaller type Sizes or Truncating Larger-Size TextUsing Fonts in AndroidIntroduce to Android O and Support Library 26 new ways of working with Fonts. now You can Bundle Fonts as Resources by Adding the Font File in the Res/Font Folder and use it like any Other Asset in XML Layouts, Styles or Programmatically via the TypefaceSpace Station Crew Member Discusses His First Days in Space with Minnesota StudentsAboard the International Space Station, Expedition 53 Flight Engineer Mark Vande Hei of NASA fielded questions about life and work on the orbital outpost during an in-flight educational event Sept. 18 with students from the Pine River-Backus schools in Pine River, MinnesotaSpace Station Crew Members Discuss Life in Space with the MediaAboard the International Space Station, Expedition 53 Flight Engineers Mark Vande Hei and Joe Acaba of NASA and Paolo Nespoli of the European Space Agency discussed life and work aboard the orbital complex in a pair of in-flight interviews Sept. 20 with KSTP-TV, Minneapolis and the Associated Press

Call / Visit for New Batch


Why Join Us

  • ➯ Free Demo Classes
  • ➯ No Registration Fee
  • ➯ Interview Questions
  • ➯ Study Materials
  • ➯ Softwares
  • ➯ Aptitude & Reasoning
  • ➯ Placement Assitance


  • MyJava Training Institute ,
  • Plot No.243 , shop No 14 ,
  • Secnd Floor , Zone-II ,
  • M.P.Nagar , Bhopal,
  • Madhya Pradesh ( 462011 )
  • ☎  08871209400 , 7987028543
  • 🌐
FacebookGoogle +LinkedInTwitterYouTube

MyJava - java Training Institute