A servlet in Java is a server-side Java class that receives requests (usually HTTP) and sends back dynamic responses (like HTML, JSON, or XML) from within a web server.

Quick Scoop: Core Idea

Think of a servlet as a tiny Java program that lives inside a web/server container (like Tomcat) and runs whenever a browser hits a specific URL. It:

  • Listens for incoming HTTP requests.
  • Processes data (business logic, database calls, validation).
  • Generates and returns a response to the client.

In modern Java, this is more formally known as a Jakarta Servlet and is part of the Jakarta EE platform, but people still casually say “Java servlet.”

Mini Definition (Exam / Interview Style)

You can remember it like this:

A servlet is a Java class that runs on the server, following the Jakarta/Java Servlet API, to handle request–response interactions (typically HTTP) and generate dynamic web content.

Key points baked into that:

  • Written in Java.
  • Runs inside a servlet container (web container).
  • Follows a standard API (Jakarta/Java Servlet API).
  • Handles request–response.

How a Servlet Fits in a Web App

When a user hits a URL, here’s what typically happens:

  1. Browser sends a request (GET, POST, etc.) to the server.
  2. The web container checks URL mappings and finds the matching servlet.
  3. It creates or reuses a servlet instance and calls its service() method.
  4. The servlet reads parameters, session data, etc., does work.
  5. It writes output (HTML/JSON/XML) to the response stream.
  6. The container sends the response back to the browser.

Often, you don’t write raw servlets anymore in big projects, because frameworks (Spring MVC, JSF, etc.) sit on top of this, but under the hood they still rely on servlet technology.

Servlet Life Cycle (In Simple Steps)

A servlet’s life cycle is controlled by the container:

  1. Loading and instantiation
    • Container loads the servlet class and creates one instance.
  2. Initialization –init()
    • Called once per servlet instance.
    • Good place for one-time setup (e.g., reading config or creating shared resources).
  3. Request handling –service() / doGet() / doPost()
    • For each incoming request, the container calls service().
    • In HttpServlet, service() dispatches to methods like doGet(), doPost(), etc.
    • You override those to implement your logic.
  4. Destruction –destroy()
    • Called once when the container decides to unload the servlet (e.g., shutdown or redeploy).
    • Use this to free resources (close connections, threads, etc.).

You can visualize the life cycle as: load → init → (service, service, service…) → destroy.

Tiny Code Sketch (Conceptual)

Here’s a simple conceptual example of an HTTP servlet:

java

import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.ServletException;
import java.io.IOException;
import java.io.PrintWriter;

@jakarta.servlet.annotation.WebServlet("/hello")
public class HelloServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {

        resp.setContentType("text/html");
        PrintWriter out = resp.getWriter();
        out.println("<html><body>");
        out.println("<h1>Hello from a Servlet!</h1>");
        out.println("</body></html>");
    }
}

When a user visits /hello, this servlet generates the HTML response.

Why Servlets Exist (and Why They Still Matter)

Before servlets, dynamic web content was often done via CGI scripts. Servlets improved this by:

  • Performance : One instance serving many requests using threads instead of spawning a new process each time.
  • Portability : Pure Java; runs anywhere a compatible container runs.
  • Integration : Fits neatly into the Java ecosystem (JDBC, JPA, Spring, etc.).
  • Standardization : Defined API, consistent behavior across containers.

Even though you might mostly work with frameworks, those frameworks use servlets underneath to handle low-level HTTP request/response.

Servlet vs JSP vs Frameworks

  • Servlets
    • Java code that writes responses.
    • Better for control logic, request processing, and backend work.
  • JSP (Jakarta Server Pages)
    • HTML with embedded Java (or tag libraries).
    • Better for views/presentation.
    • Often compiled to servlets behind the scenes.
  • Modern frameworks (Spring MVC, JSF, etc.)
    • Built on top of servlets.
    • Provide routing, binding, validation, templating, etc., so you rarely touch raw servlets directly.

A common pattern historically: Servlet = controller , JSP = view.

Quick FAQs

1. Is a servlet the same as Jakarta Servlet?

  • “Java Servlet” is the old name; it’s now part of Jakarta EE and called Jakarta Servlet , but the idea and core API are essentially the same, just under the jakarta.servlet package.

2. Do I need a special server to run servlets?

  • You need a servlet container (e.g., Tomcat, Jetty, Undertow) or a full Jakarta EE application server (e.g., WildFly, Payara, GlassFish).

3. Are servlets still relevant in 2026?

  • Yes, because many frameworks still delegate to servlets for HTTP handling, and many existing Java web apps use them directly or indirectly.

Mini Story to Remember It

Imagine a busy restaurant:

  • The browser is the customer.
  • The web server + container is the restaurant.
  • The servlet is the chef dedicated to certain dishes (URLs).
  • The request is the order slip.
  • The response is the finished plate.

The customer doesn’t see the chef directly, but every time they order a dish (hit a URL), the chef (servlet) gets the order, prepares the result, and sends it out through the wait staff (the server).

One-Line TL;DR

A servlet in Java is a server-side Java class managed by a web container that processes HTTP requests and generates dynamic responses, forming the core of many Java web applications.