How does servlet container manage servlet lifecycle in Java

The servlet container manages four phases of the servlet lifecycle:

  • Servlet class loading - when the container receives a request for a servlet, the servlet class is loaded into memory and its constructor without parameters is called.
  • Servlet class initialization - after the class is loaded, the container initializes the ServletConfig object for this servlet and injects it through the init() method. This is where the servlet class gets converted from a regular class to a servlet.
  • Handling Requests - once initialized, the servlet is ready to process requests. For each client request, the servlet container spawns a new thread and calls the service() method by passing a reference to the response and request objects.
  • Disposal - when the container is stopped or the application stops, then the servlet container destroys the servlet classes by calling the destroy() method.

Thus, servlet is created the first time it is accessed and lives for the entire duration of the application (as opposed to class objects, which are destroyed by the garbage collector after they are no longer used) and the entire servlet life cycle can be described as a sequence of method calls:

  • public void init(ServletConfig config) - used by the container to initialize the servlet. Called once in the lifetime of the servlet.
  • public void service(ServletRequest request, ServletResponse response) - called for each request. The method cannot be called before the init() method is executed.
  • public void destroy() - called to destroy the servlet (once during the lifetime of the servlet).

Read also:


Comments

Popular posts from this blog

Methods for reading XML in Java

XML, well-formed XML and valid XML

ArrayList and LinkedList in Java, memory usage and speed