Explain Servlet and Servlet lifecycle

Explain Servlet and servlet lifecycle

Certainly! Let’s dive into the world of servlets and explore their lifecycle.

Servlets: A servlet is a Java-based server-side component that dynamically generates content in response to client requests. Servlets are commonly used for web applications, handling HTTP requests and producing HTML, XML, or other formats.

Servlet Lifecycle: The lifecycle of a servlet consists of several stages:

Servlet lifecycle

Loading a Servlet lifecycle

The servlet container (like Tomcat or Jetty) loads and initializes the servlet.

  • Two operations occur during this stage:
  • Loading: The servlet class is loaded.
  • Instantiation: An instance of the servlet is created using the no-argument constructor.
  • The container may delay loading until the servlet is needed to handle a request.

Initializing a Servlet

  • After successful instantiation, the container initializes the servlet object.
  • The init(ServletConfig) method is called once, passing a ServletConfig object.
  • Resources (e.g., JDBC data sources) can be initialized here.
  • If initialization fails, the servlet throws ServletException or UnavailableException.

Handling Requests

  1. The servlet instance is ready to serve client requests.
  2. When a request arrives, the container performs these steps:
  3. Creates ServletRequest and ServletResponse objects (e.g., HttpServletRequest and HttpServletResponse for HTTP requests).
  4. Invokes the service(ServletRequest, ServletResponse) method with these objects.
  5. The service() method processes the request and may throw exceptions (e.g., ServletException, UnavailableException, or IOException).

Destroying a Servlet

When the container decides to destroy the servlet (e.g., during server shutdown or configuration changes), it:

  • Allows running threads in the service() method to complete.
  • Calls the destroy() method.
  • The servlet is then garbage-collected by the JVM.

Example
Example in Java: Here’s a simple servlet example that responds with “Hello, World!” when accessed:
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.IOException;

public class MyServlet extends HttpServlet {
    @Override
    public void init(ServletConfig config) throws ServletException {
        // Initialization code (e.g., database connections)
    }

    @Override
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html");
        response.getWriter().println("<html><body><h1>Hello, World!</h1></body></html>");
    }

    @Override
    public void destroy() {
        // Cleanup code (e.g., close resources)
    }
}

Homepage

Readmore