Servlet Tutorial

Life Cycle Methods

LIFE CYCLE METHODS of servlets:

In servlets we have three life cycle methods, they are

public void init ();
public void service (ServletRequest req, ServletResponse res); 
public void destroy ();

public void init ():

Whenever client makes a request to a servlet, the server will receive the request and it automatically calls init () method i.e., init () method will be called only one time by the server whenever we make first request.

In this method, we write the block of statements which will perform one time operations, such as, opening the file, database connection, initialization of parameters, etc.

public void service (ServletRequest, ServletResponse):

After calling init () method, service () method will be called when we make first request from second request to further subsequent requests, server will call only service method. Therefore, service () method will be called each and every time as and when we make a request.

In service () method we write the block of statements which will perform repeated operations such as retrieving data from database, retrieving data from file, modifications of parameters data, etc. Hence, in service () method we always write business logic.

Whenever control comes to service () method the server will create two objects of ServletRequest and ServletResponse interfaces.

Object of ServletRequest contains the data which is passed by client. After processing client data, the resultant data must be kept in an object of ServletResponse.

An object of ServletRequest and ServletResponse must be used always within the scope of service () method only i.e., we cannot use in init () method and destroy () method.

Once the service () method is completed an object of ServletRequest and an object of ServletResponse will be destroyed.

public void destroy ():

The destroy () method will be called by the server in two situations; they are when the server is closed and when the servlet is removed from server context. In this method we write the block of statements which are obtained in init () method.

Note: Life cycle methods are those which will be called by the server at various times to perform various operations.

Write a servlet which displays a message "I LOVE MY MOM"?

Answer:

import javax.servlet.*;
import java.io.*;

public class First extends GenericServlet {

    public First() {
        System.out.println("I AM FROM DEFAULT CONSTRUCTOR...");
    }

    public void init() {
        System.out.println("I AM FROM init METHOD...");
    }

    public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException {
        System.out.println("I LOVE MY MOM...");
        System.out.println("I AM FROM service METHOD...");
    }

    public void destroy() {
        System.out.println("I AM FROM destroy METHOD...");
    }
};