Servlet Lifecycle init, service, destroy Methods is an important Servlet topic because it appears in real projects, debugging sessions, and interviews. Learn the meaning first, then connect it to a small working example so the rule does not stay abstract.
For this page, focus on what problem Servlet Lifecycle init, service, destroy Methods solves, where developers usually make mistakes, and how to verify the result. The audit note for this lesson was: under 650 content words; limited checklist/practice/mistake/FAQ notes .
A strong understanding of Servlet Lifecycle init, service, destroy Methods should include syntax, behavior, one realistic use case, one failure case, and one quick way to check your work with tools or output.
Servlet Lifecycle init service destroy Methods should be studied as a practical Servlet lesson, not as a label. Start by naming the input, the rule that changes the input, and the result a learner should be able to predict after reading the page.
In the servlet > servlet-lifecycle page, the notes should connect the definition with a working scenario, a mistake that beginners actually make, and the exact check that proves the fix. That makes the topic useful for coding, debugging, and interview revision.
The Servlet container manages the complete lifecycle of a Servlet. The lifecycle consists of three main phases:
The container creates only one instance of each Servlet and handles concurrent requests using multiple threads. This is why Servlet instance variables must be thread-safe.
package com.example;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.WebServlet;
import java.io.*;
import java.util.concurrent.atomic.AtomicInteger;
@WebServlet("/lifecycle")
public class LifecycleServlet extends HttpServlet {
// Use AtomicInteger for thread-safe counter
private AtomicInteger requestCount = new AtomicInteger(0);
private String initMessage;
// ===== PHASE 1: INITIALIZATION =====
// Called ONCE when servlet is first loaded (or at startup if load-on-startup is set)
@Override
public void init(ServletConfig config) throws ServletException {
super.init(config);
// Read init parameters
initMessage = config.getInitParameter("message");
if (initMessage == null) initMessage = "Default message";
System.out.println("[INIT] LifecycleServlet initialized. Message: " + initMessage);
}
// ===== PHASE 2: REQUEST HANDLING =====
// service() dispatches to doGet/doPost/etc. based on HTTP method
// You can override service() directly, but it's better to override doGet/doPost
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
System.out.println("[SERVICE] Handling request #" + requestCount.incrementAndGet());
super.service(req, resp); // Delegates to doGet/doPost/etc.
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
resp.setContentType("text/html;charset=UTF-8");
PrintWriter out = resp.getWriter();
out.println("<h2>Servlet Lifecycle Demo</h2>");
out.println("<p>Init message: " + initMessage + "</p>");
out.println("<p>Total requests: " + requestCount.get() + "</p>");
out.println("<p>Thread: " + Thread.currentThread().getName() + "</p>");
}
// ===== PHASE 3: DESTRUCTION =====
// Called ONCE when servlet is removed (server shutdown or undeploy)
@Override
public void destroy() {
System.out.println("[DESTROY] LifecycleServlet destroyed. Total requests served: "
+ requestCount.get());
// Release resources: close DB connections, stop threads, etc.
}
}
By default, Servlets are loaded lazily - on the first request. You can force eager loading at startup using load-on-startup:
// loadOnStartup = 1 means load at startup, priority 1 (loads before priority 2, 3, etc.)
@WebServlet(urlPatterns = "/app", loadOnStartup = 1)
public class AppInitServlet extends HttpServlet {
@Override
public void init() throws ServletException {
// This runs at server startup
System.out.println("Application initialized at startup");
// Initialize shared resources: DB connection pool, caches, etc.
getServletContext().setAttribute("appStartTime", System.currentTimeMillis());
}
}
<servlet>
<servlet-name>AppInitServlet</servlet-name>
<servlet-class>com.example.AppInitServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet>
<servlet-name>DataServlet</servlet-name>
<servlet-class>com.example.DataServlet</servlet-class>
<load-on-startup>2</load-on-startup>
</servlet>
When studying Servlet Lifecycle init, service, destroy Methods, separate three things: the concept, the syntax, and the situation where it is useful. This prevents the lesson from becoming a list of commands with no practical meaning.
In Servlet, Servlet Lifecycle init, service, destroy Methods becomes easier when you build a tiny example first, then increase complexity. Add one realistic input, one invalid or boundary input, and one explanation of why the result changes.
class ServletLifecycleinitservicedestroyMethodsReview {
public static void main(String[] args) {
String state = "ready";
System.out.println("Servlet Lifecycle init service destroy Methods: " + state);
}
}
String value = null;
if (value == null) {
System.out.println("Servlet Lifecycle init service destroy Methods: handle the missing value before continuing");
}
Memorizing Servlet Lifecycle init service destroy Methods without the situation where it is useful.
Connect Servlet Lifecycle init service destroy Methods to a concrete Servlet task.
Testing Servlet Lifecycle init service destroy Methods only with the perfect input.
Include empty, missing, duplicate, incompatible, or failed cases when relevant.
Changing code before reading the visible symptom or error message.
Inspect the output, state, configuration, or stack trace connected to Servlet Lifecycle init service destroy Methods.
Memorizing Servlet Lifecycle init service destroy Methods without the situation where it is useful.
Connect Servlet Lifecycle init service destroy Methods to a concrete Servlet task.
The common mistake is memorizing syntax without understanding when the behavior changes or fails.
Remember the problem it solves in Servlet, then attach the syntax or steps to that problem.
You can predict the result of a small example, explain a failure case, and choose it over a nearby alternative for a clear reason.
They often copy the syntax but skip the state, input, dependency, selector, route, type, or configuration that controls the behavior.
Explore 500+ free tutorials across 20+ languages and frameworks.