Learn Java for Web Development

(Tina Meador) #1

46 CHAPTER 2: Building Web Applications Using Servlets and JSP


methods such as init(), service(), and destroy() to initialize a servlet, to service requests, and to
remove a servlet from the server, respectively. Table 2-1 describes all the methods of the
javax.servlet.Servlet interface.


Table 2-1. The Life-Cycle and Non-Life-Cycle Methods of the Servlet Interface
Modifier and Type Method
void init(ServletConfig config)
void service(ServletRequest req, ServletResponse res)
void destroy()
ServletConfig getServletConfig()
String getServletInfo()

The life-cycle methods are invoked by the container at appropriate instants in a servlet’s life in the
following sequence:



  1. The servlet is constructed and then initialized with the init method.

  2. Any calls from clients to the service method are handled.

  3. The servlet is then destroyed with the destroy method, garbage collected,
    and finalized.


The Servlet interface methods illustrated in Table 2-1 are explained here:


   init(ServletConfig): Called by the servlet container exactly once after
instantiating the servlet. This method must complete successfully before the
servlet is a candidate to receive any requests.
 service(): Called by the servlet container, after the servlet’s init() method has
completed successfully, to allow the servlet to respond to a request.
 destroy(): Called by the container to destroy the servlet and serves as a
method in which the servlet must release acquired resources before it is
destroyed.
 getServletConfig(): Allows the servlet to get start-up information in the form
of a ServletConfig object returned by this method. The ServletConfig object
contains initialization and start-up parameters for the servlet.
 getServletInfo(): Allows the servlet to return its own information such as the
servlet’s author and version.
Free download pdf