Java Servlet and Life Cycle

A Servlet is a Java Program, which runs on any Web Server(Tomcat Server, Glass Fish Server, Web Logic, Web Sphere). Servlet receives request from Web Browser on Client Machine. Below are Life cycle methods for a Servlet.

public void init(ServletConfig config);
This method is invoked when Servlet instance does not exist, and on receiving first request from Web Browser. init() method is not invoked, for each and every request. Constructor of Servlet is executed before init() method.

public void service(ServletRequest request, ServletResponse response);
This method is invoked, whenever a request is received from Web Browser. This method processes, and provides response to the Request. This method further invokes doGet() or doPost() method, based on GET or POST HTTP Request.

public void destroy();
This method is invoked, when Servlet instance gets destroyed, which may occur, when no requests, or when Web Server is shutdown, or garbage collection, to reclaim memory,etc…

import java.io.IOException;
import java.io.PrintWriter;

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 LifeCycle extends HttpServlet
{

	public LifeCycle()
	{
		System.out.println("Am from default constructor");
	}

	public void init(ServletConfig config)
	{
		System.out.println("Am from Init method...!");
	}

        public void doGet(HttpServletRequest req,HttpServletResponse res)
                throws ServletException,IOException
        {
            System.out.println("Am from doGet method...!");
            PrintWriter out = res.getWriter();

            out.println(" from doGet()
"); } public void doPost(HttpServletRequest req,HttpServletResponse res) throws ServletException,IOException { System.out.println("Am from doPost method...!"); PrintWriter out = res.getWriter(); out.println(" from doPost()
"); } public void destroy() { System.out.println("Am from Destroy methods"); } } Output(on Server Console, when request is sent to Web Server): INFO: Am from default constructor INFO: Am from Init method...! INFO: Am from doGet method...!

It is required to be aware of Servlet Life Cycle methods, to develop efficient Java Servlets.

You may also like to read:
Purpose of Filter in Servlets
How many implicit objects are in JSP
Program to send HTTP Request to Web Server