UNIT III SERVER SIDE PROGRAMMING
3.2 Servlet Lifecycle
Introduction
The Servlet lifecycle defines the stages a servlet goes through during its existence in a web application. Understanding the lifecycle helps in effectively managing resources and optimizing server-side operations. The lifecycle is managed by the servlet container (e.g., Apache Tomcat).
Stages of the Servlet Lifecycle
- 1. Loading and Instantiation
- The servlet container loads the servlet class into memory when the web server starts or when the first request is made.
- A single instance of the servlet is created using the default constructor.
- 2. Initialization (init Method)
- The container calls the
init()method once after the servlet instance is created. - This stage is for performing one-time initialization tasks, such as setting up resources or configuration.
- Code Example:
@Override public void init(ServletConfig config) throws ServletException { super.init(config); System.out.println("Servlet is initialized"); } - The container calls the
- The
service()method is invoked for every client request. - It identifies the HTTP request type (e.g., GET, POST) and calls the corresponding method (e.g.,
doGet,doPost). - Code Example:
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<h1>Hello, this is a GET response!</h1>");
}
- The
destroy()method is called once when the servlet is removed from memory, usually during server shutdown. - Use this stage for cleanup tasks, such as releasing resources or closing connections.
- Code Example:
@Override
public void destroy() {
System.out.println("Servlet is destroyed");
}
Servlet Lifecycle Diagram

Comments
Post a Comment