Java Notes
Deep dive into the Servlet lifecycle including initialization, request handling, and destruction phases with practical code examples and diagrams.
Overview
The Servlet Life Cycle defines how a servlet is loaded, initialized, handles requests, and is finally destroyed by the servlet container. Understanding this lifecycle is crucial for managing resources, database connections, and application state.
Phase 1: Loading and Instantiation
The servlet container:
- Finds the servlet class (from web.xml or @WebServlet)
- Loads the class using ClassLoader
- Creates ONE instance using the no-arg constructor
public class MyServlet extends HttpServlet {
// Constructor called ONCE by container
public MyServlet() {
System.out.println("Servlet instantiated!");
}
}Servlet instantiated!
When Does Loading Happen?
| Trigger | Explanation |
|---|---|
| First request | Default behavior — lazy loading |
| Server startup | When loadOnStartup >= 0 is set |
@WebServlet(urlPatterns = "/my-servlet", loadOnStartup = 1)
public class MyServlet extends HttpServlet { }loadOnStartup values:
- Negative (default): Load on first request
- 0 or positive: Load at server startup (lower number = higher priority)
Phase 2: Initialization — init()
Called exactly once after instantiation. Use it to perform expensive one-time setup.
@WebServlet("/users")
public class UserServlet extends HttpServlet {
private Connection dbConnection;
private String appName;
@Override
public void init(ServletConfig config) throws ServletException {
super.init(config); // IMPORTANT: always call super.init()
// Read initialization parameters
appName = config.getInitParameter("appName");
// Open database connection (one-time setup)
try {
Class.forName("com.mysql.cj.jdbc.Driver");
dbConnection = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/mydb", "root", "password"
);
System.out.println("Database connected in init()");
} catch (Exception e) {
throw new ServletException("DB connection failed", e);
}
}
}Database connected in init()
Init Parameters in web.xml
<servlet>
<servlet-name>UserServlet</servlet-name>
<servlet-class>com.example.UserServlet</servlet-class>
<init-param>
<param-name>appName</param-name>
<param-value>MyWebApp</param-value>
</init-param>
</servlet>Two Versions of init()
// Version 1: With ServletConfig (called by container)
public void init(ServletConfig config) throws ServletException {
super.init(config);
// your setup code
}
// Version 2: Convenience method (no need to call super)
public void init() throws ServletException {
// your setup code — simpler, recommended
}Phase 3: Request Handling — service()
Called for every client request. The container creates a new thread for each request.
// The service() method dispatches to appropriate handler
protected void service(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
String method = req.getMethod();
if (method.equals("GET")) {
doGet(req, resp);
} else if (method.equals("POST")) {
doPost(req, resp);
} else if (method.equals("PUT")) {
doPut(req, resp);
} else if (method.equals("DELETE")) {
doDelete(req, resp);
}
}Handling Multiple HTTP Methods
@WebServlet("/products")
public class ProductServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// Handle GET — list products
response.setContentType("application/json");
PrintWriter out = response.getWriter();
out.println("{\"products\": []}");
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// Handle POST — create product
String name = request.getParameter("name");
String price = request.getParameter("price");
// Save to database...
response.setStatus(HttpServletResponse.SC_CREATED);
response.getWriter().println("Product created: " + name);
}
@Override
protected void doPut(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// Handle PUT — update product
response.getWriter().println("Product updated");
}
@Override
protected void doDelete(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// Handle DELETE — remove product
response.getWriter().println("Product deleted");
}
}Thread Safety Issue
Phase 4: Destruction — destroy()
Called once when the container shuts down or the servlet is unloaded.
@Override
public void destroy() {
// Close database connection
try {
if (dbConnection != null && !dbConnection.isClosed()) {
dbConnection.close();
System.out.println("Database connection closed in destroy()");
}
} catch (SQLException e) {
e.printStackTrace();
}
// Release other resources
System.out.println("Servlet destroyed — cleanup complete");
}Database connection closed in destroy() Servlet destroyed — cleanup complete
Complete Lifecycle Example
1. Constructor called — Servlet instantiated 2. init() called — One-time initialization
Console Output:
ServletConfig vs ServletContext
| Feature | ServletConfig | ServletContext |
|---|---|---|
| Scope | Per servlet | Per web application |
| Access | getServletConfig() | getServletContext() |
| Purpose | Servlet-specific params | App-wide shared data |
| Set by | <init-param> | <context-param> |
// Reading context parameters (application-wide)
@Override
public void init() throws ServletException {
ServletContext context = getServletContext();
String dbUrl = context.getInitParameter("DATABASE_URL");
}Interview Key Points
- Servlet lifecycle: Constructor → init() → service() → destroy()
- Only ONE instance of a servlet is created (singleton pattern)
- Multiple threads call service() concurrently
- init() is called once; destroy() is called once
- Use
loadOnStartupto control when initialization happens - Instance variables are NOT thread-safe in servlets
init(ServletConfig)must callsuper.init(config)to save config
Summary Table
| Method | Called | Times | Purpose |
|---|---|---|---|
| Constructor | On first request or startup | Once | Create instance |
| init() | After construction | Once | Setup resources |
| service() | On each HTTP request | Many | Handle request |
| destroy() | On shutdown/unload | Once | Cleanup resources |
Exam Focus
Revise definitions, diagrams, examples, and short-answer points for Servlet Life Cycle.
Interview Use
Prepare one clear explanation, one practical example, and one common mistake for this Java Master Course topic.
Search Terms
java-master-course, java master course, java, master, course, servlets, jsp, servlet
Related Java Master Course Topics