Go Back   TechArena Community > Software > Software Development
Become a Member!
Forgot your username/password?
Tags Active Topics RSS Search Mark Forums Read

Reply
 
Thread Tools Search this Thread
  #1  
Old 07-08-2009
Member
 
Join Date: Aug 2009
Posts: 4
Explain Life Cycle of a Servlet

Hi,

Can someone explain the Life Cycle of a Servlet?

Thanks,
Coffee
Reply With Quote
  #2  
Old 07-08-2009
Member
 
Join Date: May 2008
Posts: 30
Re: Explain Life Cycle of a Servlet

Servlet Life Cycle

The life cycle 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
1. Loads the servlet class.
2. Creates an instance of the servlet class.
3. Initializes the servlet instance by calling the init method.
2. Invokes the service method, passing a request and response object.

If the container needs to remove the servlet, it finalizes the servlet by calling the servlet's destroy method.

Handling Servlet Life-Cycle Events

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

The listeners.ContextListener class creates and removes the database helper and counter objects used in the Duke's Bookstore application. The methods retrieve the Web context object from ServletContextEvent and then store (and remove) the objects as servlet context attributes.

Code:
import database.BookDB;
import javax.servlet.*;
import util.Counter;

public final class ContextListener
   implements ServletContextListener {
   private ServletContext context = null;
   public void contextInitialized(ServletContextEvent event) {
      context = event.getServletContext();
      try {
         BookDB bookDB = new BookDB();
         context.setAttribute("bookDB", bookDB);
      } catch (Exception ex) {
         System.out.println(
            "Couldn't create database: " + ex.getMessage());
      }
      Counter counter = new Counter();
      context.setAttribute("hitCounter", counter);
      context.log("Created hitCounter" + 
         counter.getCounter());
      counter = new Counter();
      context.setAttribute("orderCounter", counter);
      context.log("Created orderCounter" +
         counter.getCounter());
   }

   public void contextDestroyed(ServletContextEvent event) {
      context = event.getServletContext();
      BookDB bookDB = context.getAttribute(
         "bookDB");
      bookDB.remove();
      context.removeAttribute("bookDB");
      context.removeAttribute("hitCounter");
      context.removeAttribute("orderCounter");
   }
}
Reply With Quote
  #3  
Old 07-08-2009
Member
 
Join Date: May 2008
Posts: 13
Re: Explain Life Cycle of a Servlet

Life cycle of Servlet

The life cycle of a servlet can be categorized into four parts:

1. Loading and Inatantiation: The servlet container loads the servlet during startup or when the first request is made. The loading of the servlet depends on the attribute <load-on-startup> of web.xml file. If the attribute <load-on-startup> has a positive value then the servlet is load with loading of the container otherwise it load when the first request comes for service. After loading of the servlet, the container creates the instances of the servlet.

2. Initialization: After creating the instances, the servlet container calls the init() method and passes the servlet initialization parameters to the init() method. The init() must be called by the servlet container before the servlet can service any request. The initialization parameters persist untill the servlet is destroyed. The init() method is called only once throughout the life cycle of the servlet. The servlet will be available for service if it is loaded successfully otherwise the servlet container unloads the servlet.

3. Servicing the Request: After successfully completing the initialization process, the servlet will be available for service. Servlet creates seperate threads for each request. The sevlet container calls the service() method for servicing any request. The service() method determines the kind of request and calls the appropriate method (doGet() or doPost()) for handling the request and sends response to the client using the methods of the response object.
4. Destroying the Servlet: If the servlet is no longer needed for servicing any request, the servlet container calls the destroy() method . Like the init() method this method is also called only once throughout the life cycle of the servlet. Calling the destroy() method indicates to the servlet container not to sent the any request for service and the servlet releases all the resources associated with it. Java Virtual Machine claims for the memory associated with the resources for garbage collection.
Reply With Quote
  #4  
Old 07-08-2009
Member
 
Join Date: May 2008
Posts: 27
Re: Explain Life Cycle of a Servlet

Servlet Life Cycle

Before start writing the servlet, it is important to know the life cylce of every servlet instance created.

Servlet Life Cycle Methods

The following are the life cycle methods of a servlet instance:
* init()
* service()
* destroy()


init()

This method is called once for a servlet instance. When first time servlet is called, servlet container creates instance of that servlet and loaded into the memory. Future requests will be served by the same instance without creating the new instance. Servlet by default multithreaded application.init() method is used for inilializing servlet variables which are required to be passed from the deployment descriptor web.xml. ServletConfig is passed as the parameter to init() method which stores all the values configured in the web.xml. It is more convenient way to initialize the servlet.

service()

This method is called for the each request. This is the entry point for the every servlet request and here we have to write our businesslogic or any other processes. This method takes HttpServletRequest and HttpServletresponse as the parameters. It is not mandatory to write this method, normally developers are interested in writing doGet() or doPost() methods which is by default called from the service() method. If you override service(), it is your reponsibility to call the appropriate methods. If you are not overridden the service() method, based on the types of the request the methods will be called.

destroy()

This method will be called once for a instance. It is used for releasing any resources used by the servlet instance. Most of the times it could be database connections, Fill IO operations, etc. destroy() is called by the container when it is removing the instance from the servlet container. Servlet instance is deleted or garbage collected by the container only when the web server issues shut down or the instance is not used for a long time.
Reply With Quote
Reply

  TechArena Community > Software > Software Development
Tags: ,



Thread Tools Search this Thread
Search this Thread:

Advanced Search


Similar Threads for: "Explain Life Cycle of a Servlet"
Thread Thread Starter Forum Replies Last Post
Life cycle of a computer virus Satchel Networking & Security 4 24-01-2011 07:19 AM
Page life cycle in asp.net jEEMOOT Software Development 3 12-01-2011 02:17 PM
JSP and Servlet problem Devabrata Software Development 5 21-07-2010 12:12 AM
What are Writer Metadata Document Life Cycle? Adamaris Windows Software 5 20-04-2010 05:10 AM
Difference between Servlet & ASP Owen Fernandes Software Development 5 05-02-2010 10:53 AM


All times are GMT +5.5. The time now is 10:11 AM.