1. Explain about servlet lifecycle methods and their
syntaxes with the help of a diagram?
Servlets are managed components. They are managed by web container. Of the various
responsibilities of web container, servlet life cycle management is the most important
one. A servlet is managed through a well defined life cycle that defines how it is loaded,
instantiated ad initialized, handles requests from clients and how it is taken out of service.
The servlet life cycle methods are defined in the javax.servlet.Servlet interface of the
Servlet API that all Servlets must implement directly or indirectly by extending
GenericServlet or HttpServlet abstract classes. Most of the servlet you develop will
implement it by extending HttpServlet class.
  Init and Destroy:
Just like applets, servlets can define init() and destroy() methods. A servlet's init(ServletConfig)
method is called by the server immediately after the server constructs the servlet's instance.
Depending on the server and its configuration, this can be at any of these times:

     When the server starts

     When the servlet is first requested, just before the service() method is invoked

     At the request of the server administrator

  In any case, init() is guaranteed to be called before the servlet handles its first request.

The servlet life cycle methods defined in Servlet interface are init(), service() and
destroy(). The life cycle starts when container instantiates the object of servlet class and
calls the init() method, and ends with the container calling the destroy() method.
The syntaxes of this methods are shown below.
1)public void init(ServletConfig config) throws ServletException
  or
 public void init()
2)public void service(HttpServletRequest req, HttpServletResponse res) throws ServletException,
IOException

3)public void destroy()



The servlet life cycle consists of four steps, instantiation, initialization, request handling
and end of service.

Loading and instantiation
During this step, web container loads the servlet class and creates a new instance of the
servlet. The container can create a servlet instance at container startup or it can delay it
until the servlet is needed to service a request.

Initialization
During initialization stage of the Servlet life cycle, the web container initializes the
servlet instance by calling the init() method. The container passes an object implementing
the ServletConfig interface via the init() method. This configuration object allows the
servlet to access name-value initialization parameters from the web application

Request handling service() method
After a servlet is properly initialized, the servlet container may use it to handle client
requests. Requests are represented by request objects of type ServletRequest. The servlet
fills out response to requests by calling methods of a provided object of type
ServletResponse. These objects are passed as parameters to the service method of the
Servlet interface. In the case of an HTTP request, the objects provided by the container
are of types HttpServletRequest and HttpServletResponse.

End of service destroy() method
When servlet container determines that the servlet should be removed from the service, it
calls the destroy() method of the servlet to allow servlet to release any resources it is
using (eg. database connections or file handles). Before calling the destroy() method, the
container allows any request threads that are currently running in the service method to
complete execution within a defined time limit. Once the servlet is removed out of
service, container will not send any requests to the servlet. If the servlet needs to be put in
service again, the container will create a new servlet instance and the life cycle begins
from the initialization phase.
lifecycle of a servlet



Example:
import java.io.*;

    import javax.servlet.*;

    import javax.servlet.http.*;



    public class InitCounter extends HttpServlet

{

    int count;

     public void init(ServletConfig config) throws ServletException {

         super.init(config);

         String initial = config.getInitParameter("initial");

         try {

             count = Integer.parseInt(initial);

         }

         catch (NumberFormatException e) {

             count = 0;

         }

     }

             public void doGet(HttpServletRequest req, HttpServletResponse res)

                          throws ServletException, IOException {

                 res.setContentType("text/plain");

                PrintWriter out = res.getWriter();

               count++;

         out.println("Since loading (and with a possible initialization");
out.println("parameter figured in), this servlet has been accessed");

          out.println(count + " times.");

      }

  }



   The init() method accepts an object that implements the ServletConfig interface. It uses the
config object's getInitParameter() method to get the value for the init parameter named initial.
This method takes the name of the parameter as a String and returns the value as a String. There
is no way to get the value as any other type. This servlet therefore converts the String value to an
int or, if there's a problem, defaults to a value of 0.

Servlet lifecycle

  • 1.
    1. Explain aboutservlet lifecycle methods and their syntaxes with the help of a diagram? Servlets are managed components. They are managed by web container. Of the various responsibilities of web container, servlet life cycle management is the most important one. A servlet is managed through a well defined life cycle that defines how it is loaded, instantiated ad initialized, handles requests from clients and how it is taken out of service. The servlet life cycle methods are defined in the javax.servlet.Servlet interface of the Servlet API that all Servlets must implement directly or indirectly by extending GenericServlet or HttpServlet abstract classes. Most of the servlet you develop will implement it by extending HttpServlet class. Init and Destroy: Just like applets, servlets can define init() and destroy() methods. A servlet's init(ServletConfig) method is called by the server immediately after the server constructs the servlet's instance. Depending on the server and its configuration, this can be at any of these times: When the server starts When the servlet is first requested, just before the service() method is invoked At the request of the server administrator In any case, init() is guaranteed to be called before the servlet handles its first request. The servlet life cycle methods defined in Servlet interface are init(), service() and destroy(). The life cycle starts when container instantiates the object of servlet class and calls the init() method, and ends with the container calling the destroy() method. The syntaxes of this methods are shown below. 1)public void init(ServletConfig config) throws ServletException or public void init() 2)public void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException 3)public void destroy() The servlet life cycle consists of four steps, instantiation, initialization, request handling and end of service. Loading and instantiation During this step, web container loads the servlet class and creates a new instance of the servlet. The container can create a servlet instance at container startup or it can delay it
  • 2.
    until the servletis needed to service a request. Initialization During initialization stage of the Servlet life cycle, the web container initializes the servlet instance by calling the init() method. The container passes an object implementing the ServletConfig interface via the init() method. This configuration object allows the servlet to access name-value initialization parameters from the web application Request handling service() method After a servlet is properly initialized, the servlet container may use it to handle client requests. Requests are represented by request objects of type ServletRequest. The servlet fills out response to requests by calling methods of a provided object of type ServletResponse. These objects are passed as parameters to the service method of the Servlet interface. In the case of an HTTP request, the objects provided by the container are of types HttpServletRequest and HttpServletResponse. End of service destroy() method When servlet container determines that the servlet should be removed from the service, it calls the destroy() method of the servlet to allow servlet to release any resources it is using (eg. database connections or file handles). Before calling the destroy() method, the container allows any request threads that are currently running in the service method to complete execution within a defined time limit. Once the servlet is removed out of service, container will not send any requests to the servlet. If the servlet needs to be put in service again, the container will create a new servlet instance and the life cycle begins from the initialization phase.
  • 3.
    lifecycle of aservlet Example: import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class InitCounter extends HttpServlet { int count; public void init(ServletConfig config) throws ServletException { super.init(config); String initial = config.getInitParameter("initial"); try { count = Integer.parseInt(initial); } catch (NumberFormatException e) { count = 0; } } public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { res.setContentType("text/plain"); PrintWriter out = res.getWriter(); count++; out.println("Since loading (and with a possible initialization");
  • 4.
    out.println("parameter figured in),this servlet has been accessed"); out.println(count + " times."); } } The init() method accepts an object that implements the ServletConfig interface. It uses the config object's getInitParameter() method to get the value for the init parameter named initial. This method takes the name of the parameter as a String and returns the value as a String. There is no way to get the value as any other type. This servlet therefore converts the String value to an int or, if there's a problem, defaults to a value of 0.