Thursday, 9 October 2014

Life cycle of the servlet

A servlet is a Java programming language class that is used to extend the capabilities of servers that host applications accessed by means of a request-response programming model. Although servlets can respond to any type of request, they are commonly used to extend the applications hosted by web servers. ( more reference ).

A servlet life cycle can be defined as the entire process from its loading till its destruction.The life cycle contains following steps.
  1. Load Servlet Class.
  2. Create Instance of Servlet.
  3. Call the servlets init() method.
  4. Call the servlets service() method.  
  5. Call the servlets destroy() method.
The 1,2 and 3 steps are called only once when the servlet is loaded in application server container. By default the servlet is not loaded until the first request is received for it, however you can force the container to load the servlet when the container starts.

Step 4 is executed multiple times - once for every HTTP request to the servlet.
Step 5 is executed when the servlet container unloads the servlet.

The init() method :

The init method is designed so that it can be called only once. Once the servlet is loaded in the container the init() method is executed. The only purpose of this method is to serve some initialization for any variables in the servlet.
public void init() throws ServletException {
  // Initialization code...

The service() method :

This is the method which is called every time when an request made by the user is received by the servlet. Each time the server receives a request for a servlet, the server spawns 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 respectively.
public void service(ServletRequest request, ServletResponse response)throws ServletException, IOException{
      //Do Processing

The destroy() method :

The destroy() method is called when a servlet is unloaded by the container. Servlet is only unloaded once when server shuts down. It is used to perform some actions like closing database connections, closing threads etc.
public void destroy() {
    // Finalization code...

1 comment:

  1. Hi, Great.. Tutorial is just awesome..It is really helpful for a newbie like me.. I am a regular follower of your blog. Really very informative post you shared here. Kindly keep blogging. If anyone wants to become a Java developer learn from Java Training in Chennai. or learn thru Java Online Training from India . Nowadays Java has tons of job opportunities on various vertical industry.