Category: java
Servlet Lifecycle
Published on 30 Sep 2026
Explanation
The servlet lifecycle is controlled by the servlet container. The main stages are loading, initialization, request processing, and destruction.
Code:
Servlet Lifecycle: Loading ↓ Instantiation ↓ init() ↓ service() ↓ destroy()
Explanation
The init() method is called once when the servlet is initialized by the container.
Code:
@Override
public void init() throws ServletException {
System.out.println("Servlet initialized");
}
Explanation
The service() method receives requests and dispatches them to methods such as doGet() and doPost().
Code:
@Override
protected void service(HttpServletRequest req,
HttpServletResponse resp)
throws ServletException, IOException {
super.service(req, resp);
}
Explanation
doGet() and doPost() are called according to the HTTP request method.
Code:
GET → doGet() POST → doPost() PUT → doPut() DELETE → doDelete()
Explanation
The destroy() method is called once before the servlet is removed from the container.
Code:
@Override
public void destroy() {
System.out.println("Servlet destroyed");
}