DEV Community

Cover image for Servlet Lifecycle Explained with Practical Examples
naveen kumar
naveen kumar

Posted on

Servlet Lifecycle Explained with Practical Examples

☕ Understanding the Servlet Lifecycle in Java Web Applications

In every Java web application, thousands of user requests travel through the server every day. Whether someone is logging into an application, submitting a registration form, or retrieving dashboard data, a servlet often acts as the first point of interaction between the client and the server.

But have you ever wondered what happens behind the scenes when a servlet receives a request?

🤔 How does the server create it?

🤔 When does it initialize?

🤔 How long does it stay alive?

🤔 What happens when the application shuts down?

Understanding the Servlet Lifecycle is one of the most fundamental concepts in Java web development. It helps developers build efficient, scalable, and high-performance applications while avoiding common mistakes related to resource management and application performance.


🚀 What is a Servlet?

A Servlet is a Java class that runs on a web server and handles client requests.

It acts as a bridge between:

✅ Web Browsers (Clients)

✅ Web Servers

✅ Backend Business Logic

✅ Databases

In modern Java Full Stack applications, servlets form the foundation of many web frameworks and enterprise applications.

Common Examples

✅ User Login

✅ Registration Forms

✅ Product Search

✅ Payment Processing

✅ Dashboard Data Retrieval

Whenever a user sends a request, a servlet processes it and generates a response.


🎯 Why Understanding the Servlet Lifecycle Matters

Many beginners learn servlet coding without understanding how a servlet behaves inside the server.

This often leads to:

❌ Memory Leaks

❌ Resource Wastage

❌ Slow Application Performance

❌ Thread-Safety Issues

❌ Poor Scalability

Enterprise organizations expect Java developers to understand servlet lifecycle management because it directly impacts:

✅ Application Performance

✅ Server Resource Utilization

✅ Scalability

✅ Reliability

If you're preparing for Java Full Stack interviews, servlet lifecycle questions are extremely common.


🔄 What is the Servlet Lifecycle?

The Servlet Lifecycle defines the stages through which a servlet passes from creation until destruction.

The servlet container (such as Apache Tomcat) manages the entire lifecycle.

The Lifecycle Consists of Three Major Phases

✅ Initialization

✅ Request Processing

✅ Destruction


🏗️ Servlet Lifecycle Architecture

Client Request
       │
       ▼
Web Server (Tomcat)
       │
       ▼
Load Servlet Class
       │
       ▼
Create Servlet Object
       │
       ▼
init()
       │
       ▼
service()
       │
       ▼
service()
       │
       ▼
service()
       │
       ▼
destroy()
       │
       ▼
Servlet Removed
Enter fullscreen mode Exit fullscreen mode

The container controls every stage automatically.

Developers only implement the required methods.


⭐ The Three Important Lifecycle Methods

Every servlet lifecycle revolves around three methods:

public void init()

public void service()

public void destroy()
Enter fullscreen mode Exit fullscreen mode

Let's understand each phase in detail.


🔹 Phase 1: Servlet Initialization (init())

When a servlet is requested for the first time, the container performs the following steps.


📌 Step 1: Load Servlet Class

public class LoginServlet extends HttpServlet
{
}
Enter fullscreen mode Exit fullscreen mode

The servlet class is loaded into memory.


📌 Step 2: Create Servlet Object

LoginServlet servlet = new LoginServlet();
Enter fullscreen mode Exit fullscreen mode

Generally, only one servlet instance is created.

This is important because the same instance handles multiple requests.


📌 Step 3: Call init()

public void init() throws ServletException
{
    System.out.println("Servlet Initialized");
}
Enter fullscreen mode Exit fullscreen mode

Output

Servlet Initialized
Enter fullscreen mode Exit fullscreen mode

The init() method executes only once during the servlet's lifetime.


🎯 Real-World Usage of init()

Developers commonly use init() for:

✅ Database Connection Setup

✅ Reading Configuration Files

✅ Loading Application Settings

✅ Creating Connection Pools

✅ Initializing Caches

Example

public void init()
{
    System.out.println("Database Connection Established");
}
Enter fullscreen mode Exit fullscreen mode

Instead of reconnecting for every request, initialization happens only once.

This significantly improves application performance.


🔹 Phase 2: Request Processing (service())

After initialization, the servlet is ready to process incoming requests.

Whenever a client sends a request:

Browser → Servlet → Response
Enter fullscreen mode Exit fullscreen mode

The container calls:

service()
Enter fullscreen mode Exit fullscreen mode

Example

public void service(
    ServletRequest request,
    ServletResponse response)
{
    System.out.println("Request Received");
}
Enter fullscreen mode Exit fullscreen mode

Every request triggers the service() method.


⚙️ Understanding How service() Works

The service() method identifies the request type:

✅ GET

✅ POST

✅ PUT

✅ DELETE

Then forwards the request to the appropriate method.

✅ doGet()

✅ doPost()

✅ doPut()

✅ doDelete()


🌐 Example Using doGet()

@WebServlet("/welcome")
public class WelcomeServlet extends HttpServlet
{
    protected void doGet(
        HttpServletRequest request,
        HttpServletResponse response)
    {
        System.out.println("GET Request Processed");
    }
}
Enter fullscreen mode Exit fullscreen mode

URL

http://localhost:8080/welcome
Enter fullscreen mode Exit fullscreen mode

Output

GET Request Processed
Enter fullscreen mode Exit fullscreen mode

📝 Example Using doPost()

protected void doPost(
    HttpServletRequest request,
    HttpServletResponse response)
{
    System.out.println("POST Request Processed");
}
Enter fullscreen mode Exit fullscreen mode

Common Uses:

✅ Login Forms

✅ Registration Forms

✅ Payment Forms

✅ User Data Submission


👥 What Happens During Multiple Requests?

Suppose 100 users access a servlet simultaneously.

Many beginners assume:

100 Users
=
100 Servlet Objects
Enter fullscreen mode Exit fullscreen mode

❌ This is incorrect.

The container generally creates:

✅ 1 Servlet Object

✅ 100 Threads

Architecture

Servlet Object
     │
 ┌───┼───┐
 │   │   │
T1  T2  T3
 │   │   │
User Requests
Enter fullscreen mode Exit fullscreen mode

Benefits

✅ Better Performance

✅ Memory Efficiency

✅ Scalability


⚠️ Important Thread-Safety Consideration

Since multiple threads share the same servlet instance, developers should avoid storing request-specific data in instance variables.

❌ Bad Practice

public class UserServlet extends HttpServlet
{
    String username;

    protected void doGet(...)
    {
        username = request.getParameter("name");
    }
}
Enter fullscreen mode Exit fullscreen mode

This can create data conflicts between users.


✅ Better Approach

protected void doGet(...)
{
    String username =
        request.getParameter("name");
}
Enter fullscreen mode Exit fullscreen mode

Always prefer local variables whenever possible.


🔹 Phase 3: Servlet Destruction (destroy())

When the application stops or the server shuts down, the container calls:

destroy()
Enter fullscreen mode Exit fullscreen mode

Example

public void destroy()
{
    System.out.println("Servlet Destroyed");
}
Enter fullscreen mode Exit fullscreen mode

Output

Servlet Destroyed
Enter fullscreen mode Exit fullscreen mode

The destroy() method executes only once.


🧹 Real-World Usage of destroy()

Common cleanup tasks include:

✅ Closing Database Connections

✅ Releasing Resources

✅ Closing File Streams

✅ Stopping Background Processes

✅ Cleaning Memory Caches

Example

public void destroy()
{
    connection.close();
}
Enter fullscreen mode Exit fullscreen mode

Proper cleanup prevents memory leaks and improves server stability.


💻 Complete Servlet Lifecycle Example

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class DemoServlet extends HttpServlet
{
    public void init()
    {
        System.out.println("Servlet Initialized");
    }

    protected void doGet(
        HttpServletRequest request,
        HttpServletResponse response)
        throws IOException
    {
        System.out.println("Request Processed");

        response.getWriter()
                .println("Hello User");
    }

    public void destroy()
    {
        System.out.println("Servlet Destroyed");
    }
}
Enter fullscreen mode Exit fullscreen mode

📈 Execution Flow

Server Starts
      │
      ▼
init()
      │
      ▼
doGet()
      │
      ▼
doGet()
      │
      ▼
doGet()
      │
      ▼
destroy()
Enter fullscreen mode Exit fullscreen mode

⏳ Lifecycle Timeline Visualization

Application Startup
       │
       ▼
Servlet Loaded
       │
       ▼
init()
       │
       ▼
--------------------------------
User Request 1 → service()
User Request 2 → service()
User Request 3 → service()
User Request 4 → service()
--------------------------------
       │
       ▼
Application Shutdown
       │
       ▼
destroy()
Enter fullscreen mode Exit fullscreen mode

This lifecycle remains consistent across Java web applications.


🏢 Servlet Lifecycle in Enterprise Applications

Large-scale enterprise systems such as:

✅ Banking Applications

✅ E-Commerce Platforms

✅ Healthcare Systems

✅ Insurance Portals

✅ ERP Solutions

rely heavily on servlet lifecycle management.

Understanding the lifecycle helps engineers:

✅ Optimize Server Performance

✅ Improve Request Handling

✅ Manage Resources Efficiently

✅ Reduce Response Time

✅ Build Scalable Applications


🌱 How Servlet Lifecycle Relates to Spring Boot

Many developers move directly to Spring Boot and skip servlet fundamentals.

However, Spring Boot itself runs on embedded servlet containers such as:

✅ Apache Tomcat

✅ Jetty

✅ Undertow

Behind the Scenes

Spring Controller
        │
        ▼
DispatcherServlet
        │
        ▼
Servlet Container
Enter fullscreen mode Exit fullscreen mode

Understanding servlet lifecycle makes it easier to understand:

✅ Spring MVC

✅ DispatcherServlet

✅ Request Handling

✅ Filters

✅ Interceptors


🎤 Common Interview Questions

❓ How many times is init() called?

✅ Only once during the servlet lifecycle.

❓ How many times is service() called?

✅ Once for every incoming request.

❓ How many times is destroy() called?

✅ Only once before servlet removal.

❓ Who manages the servlet lifecycle?

✅ The Servlet Container (Tomcat, Jetty, etc.)

❓ Can multiple users share one servlet object?

✅ Yes. A single servlet instance generally serves multiple users through multiple threads.


💡 Best Practices for Servlet Development

✅ Keep init() Lightweight

Avoid heavy processing during startup.

✅ Use Connection Pools

Never create database connections repeatedly.

✅ Avoid Instance Variables

Prevent thread-safety issues.

✅ Release Resources in destroy()

Always clean up resources properly.

✅ Log Lifecycle Events

Useful for debugging production applications.


🤖 Why This Knowledge Still Matters in the AI Era

With the rise of Generative AI and Agentic AI, modern applications increasingly rely on backend APIs and scalable server architectures.

Even AI-powered systems require:

✅ Request Processing

✅ API Communication

✅ Session Management

✅ Authentication

✅ Database Interaction

Many of these backend operations are ultimately handled through servlet-based infrastructures.

Whether you're building traditional web applications or integrating AI-driven services, understanding the servlet lifecycle provides a strong foundation for designing robust server-side systems.


🎯 Career Perspective for Java Developers

If you're pursuing a career in Java Full Stack development, mastering servlet lifecycle concepts is essential.

Employers expect developers to understand:

✅ Core Java

✅ Servlets

✅ JSP

✅ JDBC

✅ Spring Boot

✅ Microservices

✅ REST APIs

✅ Cloud Deployment

Many Java Full Stack training programs include servlet lifecycle as a foundational topic because it builds the conceptual understanding required for advanced frameworks.


🏆 Final Thoughts

The Servlet Lifecycle is one of the most fundamental concepts in Java web development.

It explains how a servlet is:

✅ Created

✅ Initialized

✅ Processes Requests

✅ Destroyed

Understanding the lifecycle allows developers to:

✅ Write Efficient Web Applications

✅ Manage Resources Effectively

✅ Improve Scalability

✅ Prevent Thread-Safety Issues

✅ Build Production-Ready Enterprise Systems

The Three Core Lifecycle Methods

🚀 init() → Initialization

⚙️ service() → Request Processing

🧹 destroy() → Cleanup

Although modern frameworks abstract much of this complexity, the servlet lifecycle remains the backbone of Java web application architecture.

Mastering it provides a deeper understanding of how web servers operate and prepares developers for advanced Java Full Stack and enterprise software development roles.

Top comments (0)