Servlet in Java

Life cycle of a servlet
Three methods are central to the life cycle of a servlet. These are init(), service(), and destroy(). They are implemented by every servlet and are invoked at specific times by the server.
  • During initialization stage of the servlet life cycle, the web container initializes the servlet instance by calling the init() method, passing an object implementing the javax.servlet.ServletConfig interface. This configuration object allows the servlet to access name-value initialization parameters from the web application.
  • After initialization, the servlet instance can service client requests. Each request is serviced in its own separate thread. The web container calls the service() method of the servlet for every request. The service() method determines the kind of request being made and dispatches it to an appropriate method to handle the request. The developer of the servlet must provide an implementation for these methods. If a request is made for a method that is not implemented by the servlet, the method of the parent class is called, typically resulting in an error being returned to the requester.
  • Finally, the web container calls the destroy() method that takes the servlet out of service. The destroy() method, like init(), is called only once in the lifecycle of a servlet.
The following is a typical user scenario of these methods.
  1. Assume that a user requests to visit a URL. The browser then generates an HTTP request for this URL.This request is then sent to the appropriate server
  2. The HTTP request is received by the web server and forwarded to the servlet container.         The container maps this request to a particular servlet.The servlet is dynamically retrieved and loaded into the address space of the container.
  3. The container invokes the init() method of the servlet. This method is invoked only when the servlet is first loaded into memory. It is possible to pass initialization parameters to the servlet so that it may configure itself.
  4. The container invokes the service() method of the servlet. This method is called to process the HTTP request. The servlet may read data that has been provided in the HTTP request.The servlet may also formulate an HTTP response for the client.The servlet remains in the container's address space and is available to process any other HTTP requests received from clients.The service() method is called for each HTTP request.The container may, at some point, decide to unload the servlet from its memory.
  5. The container calls the servlet's destroy() method to relinquish any resources such as file handles that are allocated for the servlet; important data may be saved to a persistent store.The memory allocated for the servlet and its objects can then be garbage collected.

No comments:

Post a Comment