Java Servlet LifeCycle Example

If you are all set to attend an interview related to J2EE/Java Web application development then, it is recommended to brush up this important concept.I witnessed this question in telephonic round interview. Today I am documenting it for future reference and for others.

What is Servlet ?: A Servlet is a Java program that runs within a servlet container. Servlets receive and respond to requests from Web clients. Servlets could in principle communicate over any client–server protocol, but they are most often used with the HTTP protocol. Thus "servlet" is often used as shorthand for "HTTP servlet". As every object is having a life-cycle so as of servlet instance.

The life-cycle of a servlet is controlled by the container in which the servlet has been deployed. Life cycle of servlet can be broadly divided into three stages :
1. Initialization stage -  init() -   Executed only once
2. Service stage -            service() -     For each request
3. Destroy stage. -          destroy() -     Executed only once 
 We can represent all three method executing in servlet container as follows :
1. Initialization phase: In this stage web-container initializes the servlet instance by calling the init() method and ONE instance per JVM for each servlet is created. It is important to note that the init() method can be invoked in either of two ways :
1. On-demand basis - On arrival of a first HTTP request for the given servlet.


2. On Servlet container start: - When servlet container start,it reads the web.xml ,finds the declared servlets in the classpath and if <load-on-startup> is configured with an integer value 0 or more then for the given servlet one instance of that servlet will be created and are stored in memory and reused every time the request arrives. (Always remember REUSED !!).Sample code for servlet config of load-on-startup:
<servlet>
<servlet-name>controlServlet</servlet-name>
//Mapping details …..
<load-on-startup> 1 </load-on-startup>
</servlet>
Note : load-on-startup can specify an (optional) integer value. If the value is greater than 0, it indicates an order for servlets to be loaded, servlets with higher numbers get loaded after servlets with lower numbers.
Please note, init(ServletConfig) is being called by the servlet container to indicate a servlet that the servlet is being placed into service.We can override this init() method .
public void init(ServletConfig config) throws ServletException
{
//some initialization - like getting database connection,
// resource management etc.
} 
hERE is a visual explanation of Instantiation phase, in layman terminology.
Notes :
init() is not the entry point of a servlet. servlet constructor is executed before execution of init() but it is not recommended to use constructor for any Servlet.
The container would decide how many instances of servlet would be instantiated upfront to cater the requests.This is container implementation..(Confused !! But it's fact)

2. Service phase : In this stage for every new request a new thread is created or allocated from a pool to invoke that servlet instance which was created in earlier stage . The HttpRequest and HttpResponse objects will be new for each new request.
One commonly asked question in interview : How HTTP request coming from web client is served by servlet ?
On request arrival web container(servlet container) calls service() method of servlet and 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 response object. Lets consider following code blocks:
public class SimpleHttpServlet extends HttpServlet {
  protected void doGet( HttpServletRequest request,
                        HttpServletResponse response)
        throws ServletException, IOException {
      response.getWriter().write("<html><body>GET response</body></html>");
  }
  protected void doPost( HttpServletRequest request,
                         HttpServletResponse response)
      throws ServletException, IOException {
      response.getWriter().write("GET/POST response");
  }
}
HttpServlet(javax.servlet.http.HttpServle) class reads the HTTP request(coming from client), and determines if the request is an HTTP GET, POST, PUT, DELETE, HEAD etc. and calls one the corresponding method. 
Notes :
It is important to note that each request is served by a new thread if and only if our servlet is not implementing SingleThreadModel interface. It is not recommended to use SingleThreadModel interface.
Is servlet threadsafe ? Answer is : No, but we can make by it thread-safe by following some standard so that it can serve multiple request in thread safe manner. 

3. Destroy phase : When a servlet is unloaded by the servlet container, its destroy() method is called. It is executed only once in servlet life cycle. A servlet is unloaded by the container if the container shuts down, or if the container reloads the whole web application at run-time.

Related blog:

[Java collection example program](http://candidjava.com/tutorial/collections-in-java-with-examples/)