Tutorials Logic
Tutorials Logic, IN info@tutorialslogic.com
Navigation
Home About Us Contact Us Blogs FAQs
Tutorials
All Tutorials
Services
Academic Projects Resume Writing Website Development
Practice
Quiz Challenge Interview Questions Certification Practice
Tools
Online Compiler JSON Formatter Regex Tester CSS Unit Converter Color Picker
Compiler Tools

What is Servlet and How Does it Work? Complete Guide 2026

Servlet Introduction

A Servlet is a Java server-side component that handles requests and generates responses. Servlets are mainly used to build dynamic web applications, process forms, create controller layers, manage sessions, return HTML or JSON, and connect browser requests to Java business logic.

A Servlet does not run like a normal main() program. It runs inside a Servlet container, also called a web container. The container receives HTTP requests, maps URLs to Servlets, creates request and response objects, manages the Servlet lifecycle, handles threading, and sends the final response back to the client.

  • Servlets are Java classes used for server-side web development.
  • They run inside a Servlet container such as Apache Tomcat, Jetty, WildFly, or GlassFish.
  • They commonly extend HttpServlet.
  • They handle HTTP methods such as GET, POST, PUT, and DELETE.
  • They are the foundation behind many Java web frameworks.

What Problem Do Servlets Solve?

A static HTML page always returns the same content. A Servlet can generate different responses based on request data, logged-in user, database records, form input, headers, cookies, or session state.

RequirementHow Servlet Helps
Process a login formReads username and password from the request.
Show user-specific contentUses session data or database records.
Return JSON for an APISets response type and writes JSON output.
Upload a fileReads multipart request data.
Protect pagesWorks with filters, sessions, and authentication logic.
Connect to a databaseCalls service/DAO classes and returns results.

Servlet Container

The Servlet container is the runtime environment for Servlets. It sits between the web server and your Java code. Apache Tomcat is one of the most common Servlet containers for learning and deployment.

Container ResponsibilityDescription
URL mappingFinds which Servlet should handle a request.
Lifecycle managementLoads, initializes, calls, and destroys Servlet instances.
Thread managementAllows one Servlet instance to serve many requests concurrently.
Request/response creationProvides HttpServletRequest and HttpServletResponse.
Session managementTracks users across requests with HttpSession.
DeploymentLoads WAR files and web application configuration.

How a Servlet Request Works

When a browser or API client sends a request, the container follows a clear request-processing flow.

  1. The client sends an HTTP request, such as GET /hello?name=Asha.
  2. The web server receives the request and passes it to the Servlet container.
  3. The container checks URL mappings and finds the matching Servlet.
  4. If needed, the container creates and initializes the Servlet.
  5. The container creates request and response objects.
  6. The container calls service(), which dispatches to doGet(), doPost(), or another method.
  7. The Servlet reads request data and writes the response.
  8. The container sends the response back to the client.

Servlet API Hierarchy

The Servlet API defines the contracts and classes used by Servlet applications. For HTTP web applications, HttpServlet is the most important base class.

TypePurpose
ServletCore interface that defines init(), service(), and destroy().
GenericServletProtocol-independent abstract class.
HttpServletHTTP-specific class with doGet(), doPost(), doPut(), and doDelete().
HttpServletRequestRepresents incoming request data.
HttpServletResponseRepresents outgoing response data.
HttpSessionStores user-specific data across requests.
ServletContextStores application-wide information and resources.
ServletConfigProvides Servlet-specific initialization configuration.

javax.servlet vs jakarta.servlet

Older Java EE Servlet applications use javax.servlet packages. Newer Jakarta EE applications use jakarta.servlet. The core ideas are the same, but the package names and compatible server versions differ.

StackPackageCommon ServerMaven Artifact
Java EE / Servlet 4javax.servletTomcat 9javax.servlet-api
Jakarta EE / Servlet 5+jakarta.servletTomcat 10+jakarta.servlet-api
Maven Dependency Examples
<dependency>
  <groupId>jakarta.servlet</groupId>
  <artifactId>jakarta.servlet-api</artifactId>
  <version>6.0.0</version>
  <scope>provided</scope>
</dependency>
<dependency>
  <groupId>javax.servlet</groupId>
  <artifactId>javax.servlet-api</artifactId>
  <version>4.0.1</version>
  <scope>provided</scope>
</dependency>

Basic Servlet Example

A simple Servlet extends HttpServlet and overrides an HTTP method such as doGet(). The @WebServlet annotation maps the class to a URL.

HelloServlet.java
package com.example;

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

@WebServlet("/hello")
public class HelloServlet extends HttpServlet {

  @Override
  protected void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    String name = request.getParameter("name");
    if (name == null || name.isBlank()) {
      name = "World";
    }

    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();

    out.println("<!DOCTYPE html>");
    out.println("<html><body>");
    out.println("<h1>Hello, " + name + "!</h1>");
    out.println("</body></html>");
  }
}

After deployment, a request such as /hello?name=Asha calls this Servlet and returns an HTML response.

Servlet Lifecycle

The Servlet container controls the lifecycle. A Servlet is typically created once and reused for many requests. This is important for performance, but it also means you must be careful with shared data.

PhaseMethodWhen It Runs
LoadingClass loadingThe container loads the Servlet class.
InstantiationConstructorThe container creates a Servlet object.
Initializationinit()Called once before handling requests.
Request handlingservice()Called for each request.
HTTP handlingdoGet(), doPost()Called based on HTTP method.
Destructiondestroy()Called once before the Servlet is removed.
Lifecycle Methods
@WebServlet(value = "/status", loadOnStartup = 1)
public class StatusServlet extends HttpServlet {

  @Override
  public void init() throws ServletException {
    System.out.println("StatusServlet initialized once");
  }

  @Override
  protected void doGet(HttpServletRequest request, HttpServletResponse response)
      throws IOException {
    response.setContentType("text/plain");
    response.getWriter().println("Server is running");
  }

  @Override
  public void destroy() {
    System.out.println("StatusServlet destroyed once");
  }
}

HTTP Methods in Servlets

HttpServlet provides method handlers for common HTTP methods. You override the handler that matches the request type your Servlet should process.

HTTP MethodServlet MethodCommon Use
GETdoGet()Read or display data.
POSTdoPost()Submit forms or create data.
PUTdoPut()Update existing data.
DELETEdoDelete()Delete data.
HEADdoHead()Return headers without body.
OPTIONSdoOptions()Describe supported methods.
GET and POST Example
@WebServlet("/login")
public class LoginServlet extends HttpServlet {

  @Override
  protected void doGet(HttpServletRequest request, HttpServletResponse response)
      throws IOException {
    response.sendRedirect("login.html");
  }

  @Override
  protected void doPost(HttpServletRequest request, HttpServletResponse response)
      throws IOException {
    String email = request.getParameter("email");
    String password = request.getParameter("password");

    if ("admin@example.com".equals(email) && "secret".equals(password)) {
      response.getWriter().println("Login successful");
    } else {
      response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
      response.getWriter().println("Invalid credentials");
    }
  }
}
<form action="/login" method="post">
  <label for="email">Email</label>
  <input id="email" name="email" type="email">

  <label for="password">Password</label>
  <input id="password" name="password" type="password">

  <button type="submit">Login</button>
</form>

Request Object

HttpServletRequest contains everything the client sent: URL path, parameters, headers, cookies, body data, session reference, and request metadata.

Reading Request Data
String name = request.getParameter("name");
String method = request.getMethod();
String uri = request.getRequestURI();
String userAgent = request.getHeader("User-Agent");
Cookie[] cookies = request.getCookies();
HttpSession session = request.getSession();

Response Object

HttpServletResponse controls what the server sends back. You can set content type, status code, headers, cookies, redirects, and response body.

Writing Responses
response.setContentType("text/html;charset=UTF-8");
response.setStatus(HttpServletResponse.SC_OK);

PrintWriter out = response.getWriter();
out.println("<h1>Welcome</h1>");
response.setContentType("application/json;charset=UTF-8");
response.setStatus(HttpServletResponse.SC_OK);

PrintWriter out = response.getWriter();
out.print("{\"status\":\"ok\"}");

Servlet Mapping

A Servlet must be mapped to one or more URL patterns. Mapping can be done with annotations or with web.xml. Annotation mapping is common for simple projects; web.xml is useful for centralized configuration.

URL Mapping
@WebServlet(
  name = "ProductServlet",
  urlPatterns = {"/products", "/products/*"},
  loadOnStartup = 1
)
public class ProductServlet extends HttpServlet {
  // Servlet code
}
<servlet>
  <servlet-name>ProductServlet</servlet-name>
  <servlet-class>com.example.ProductServlet</servlet-class>
  <load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
  <servlet-name>ProductServlet</servlet-name>
  <url-pattern>/products/*</url-pattern>
</servlet-mapping>

ServletContext and ServletConfig

ServletConfig stores configuration for one Servlet. ServletContext stores application-wide information shared across the web application.

ObjectScopeCommon Use
ServletConfigSingle ServletServlet-specific init parameters.
ServletContextWhole web appApplication attributes, resources, logging, shared config.
Config and Context
String servletValue = getServletConfig().getInitParameter("mode");

ServletContext context = getServletContext();
String appName = context.getInitParameter("appName");
context.setAttribute("totalUsers", 100);

Session Management

HTTP is stateless, meaning each request is independent. Servlets use HttpSession, cookies, or URL rewriting to remember users across multiple requests.

Using HttpSession
HttpSession session = request.getSession();
session.setAttribute("userEmail", email);

String userEmail = (String) session.getAttribute("userEmail");

session.invalidate(); // logout

Thread Safety in Servlets

A Servlet instance can handle many requests at the same time using different threads. This means instance variables are shared and can cause bugs if they store request-specific data.

Thread Safety
public class UnsafeServlet extends HttpServlet {
  private String currentUser; // shared by all requests

  protected void doGet(HttpServletRequest request, HttpServletResponse response) {
    currentUser = request.getParameter("user");
  }
}
public class SafeServlet extends HttpServlet {

  protected void doGet(HttpServletRequest request, HttpServletResponse response) {
    String currentUser = request.getParameter("user"); // local to this request
  }
}

Forward vs Redirect

Servlets can forward a request to another server-side resource or redirect the browser to a new URL. These actions look similar but behave differently.

ActionWhere It HappensBrowser URL Changes?Use Case
ForwardServerNoSend request to JSP or another Servlet.
RedirectClientYesSend user to another page after form submission.
Forward and Redirect
// Server-side forward
request.getRequestDispatcher("/WEB-INF/views/profile.jsp")
       .forward(request, response);

// Client-side redirect
response.sendRedirect(request.getContextPath() + "/login");

Filters and Listeners Around Servlets

Filters and listeners are related Servlet technologies. A filter can run before and after a request reaches a Servlet. A listener reacts to lifecycle events such as application startup, session creation, or request creation.

ComponentPurposeExample
ServletHandles a request and creates a response.ProductServlet
FilterIntercepts requests/responses.AuthenticationFilter, LoggingFilter
ListenerResponds to lifecycle events.ServletContextListener

Servlets in MVC Architecture

In classic Java web MVC, the Servlet usually acts as the controller. It reads the request, calls service classes, stores results in request attributes, and forwards to a JSP view.

Servlet as Controller
@WebServlet("/products")
public class ProductServlet extends HttpServlet {
  private final ProductService productService = new ProductService();

  @Override
  protected void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    List<Product> products = productService.findAll();
    request.setAttribute("products", products);
    request.getRequestDispatcher("/WEB-INF/views/products.jsp")
           .forward(request, response);
  }
}

Servlet vs JSP

Servlets and JSP are often used together. A Servlet is better for Java control logic. JSP is better for rendering HTML views. In MVC, Servlets should not contain large amounts of HTML, and JSP should not contain large amounts of Java logic.

FeatureServletJSP
Primary roleController and request handling.View rendering.
Written asJava class.HTML-like page with JSP tags.
Best forBusiness flow, validation, routing.Displaying dynamic HTML.
Bad useWriting huge HTML strings.Writing complex Java logic.

Servlet vs CGI

Before Servlets, CGI was a common approach for dynamic server-side content. Servlets improved performance by using a managed Java runtime and threads instead of starting a new process for each request.

FeatureServletCGI
Execution modelContainer-managed, usually multi-threaded.Often one process per request.
PerformanceEfficient for repeated requests.Process startup can be expensive.
Session supportBuilt-in APIs.Usually manual.
PortabilityRuns on Java Servlet containers.Depends on server and script environment.

Deployment Basics

Servlet applications are commonly packaged as WAR files and deployed to a Servlet container. The standard project structure keeps Java code, web resources, libraries, and configuration in known locations.

Typical Servlet Project Structure
servlet-demo/
  src/main/java/com/example/
    HelloServlet.java
  src/main/webapp/
    index.html
    WEB-INF/
      web.xml
      views/
        products.jsp
  pom.xml

Where Servlets Are Used

  • Processing forms such as login, registration, search, and checkout.
  • Building controller layers for MVC web applications.
  • Returning JSON for Java-based APIs.
  • Managing sessions, cookies, and authentication flow.
  • Handling file upload and download.
  • Connecting web requests to service and database layers.
  • Supporting filters, listeners, and application lifecycle tasks.

Conclusion

Servlets are a core part of Java web development. They connect HTTP requests to Java code, read input, call application logic, manage sessions, and generate responses. Even when using frameworks such as Spring MVC, understanding Servlets helps you understand what happens underneath every Java web request.

To master Servlets, focus on the container, lifecycle, request and response objects, URL mapping, HTTP methods, sessions, thread safety, filters, listeners, MVC flow, and deployment. These concepts form the base for the rest of Java web programming.

Common Mistakes to Avoid
WRONG Store request-specific data in Servlet instance variables
RIGHT Use local variables, request attributes, or session attributes
A Servlet instance can serve many requests at the same time.
WRONG Use GET for passwords or state-changing actions
RIGHT Use POST for sensitive or state-changing form submissions
GET parameters appear in URLs and are intended for safe read operations.
WRONG Mix javax.servlet imports with Tomcat 10+
RIGHT Use jakarta.servlet imports with Tomcat 10+
Match your imports, dependencies, and server version.
WRONG Write large HTML pages using PrintWriter
RIGHT Forward to JSP or a template view for complex HTML
Servlets are best used as controllers, not view templates.
WRONG Forget to set content type
RIGHT Set response content type before writing output
Use text/html for HTML and application/json for JSON responses.
Key Takeaways
  • A Servlet is a Java server-side component that handles requests and responses.
  • Servlets run inside a Servlet container such as Tomcat or Jetty.
  • HttpServlet provides HTTP method handlers such as doGet() and doPost().
  • HttpServletRequest reads input; HttpServletResponse writes output.
  • The container manages lifecycle, mapping, threading, sessions, and deployment.
  • Servlets are commonly used as controllers in MVC web applications.
  • Thread safety matters because one Servlet instance can handle many requests.

Frequently Asked Questions


Level Up Your Servlet Skills

Master Servlet with these hand-picked resources

10,000+ learners
Free forever
Updated 2026

Ready to Level Up Your Skills?

Explore 500+ free tutorials across 20+ languages and frameworks.