Skip to content
Tutorials Center
My learning

Topics

Lesson 35 of 119 ยท Servlets and JSP

Servlets

Learn Jakarta Servlets - HttpServlet, doGet and doPost, @WebServlet mappings, request and response objects, HTML and JSON output, and the threading rules.

A servlet is a Java class that receives an HTTP request and produces a response, running inside a container such as Tomcat or Jetty. It is the oldest and most fundamental web API in Java, and it is still everywhere: Spring MVC's DispatcherServlet is a servlet, Jakarta REST implementations run on servlets, and JSP pages are compiled into servlets. When a Spring controller method receives an HttpServletRequest parameter, it is the very object this lesson is about.

You will learn how a servlet is written and mapped to URLs, what the request and response objects offer, how to produce HTML and JSON safely, and the single most important rule of servlet programming: one instance serves many threads at once. The Servlet API needs a container, which can't run on this page, so the real code is shown read-only. Each idea is also demonstrated in a runnable program, including a miniature servlet container built on the JDK's HttpServer that copies the real API's shape. If containers and WAR files are new to you, read the Jakarta EE Overview first.

How a request reaches a servlet

When a browser requests https://example.com/shop/hello?name=Ada, the container does all the heavy lifting before your code runs:

  1. A connector accepts the TCP connection (and TLS) and parses the HTTP request.
  2. A worker thread from the container's thread pool takes over the request.
  3. The container picks the web application by context root (/shop), then the servlet whose URL pattern matches the rest of the path (/hello).
  4. It builds an HttpServletRequest and an HttpServletResponse, runs any filters (see Filters and Listeners), and calls the servlet's service method.
  5. HttpServlet.service looks at the HTTP method and calls doGet, doPost, doPut, doDelete and so on.
  6. When the method returns, the container sends whatever the servlet wrote to the response, and the thread goes back to the pool.

Your first servlet

A servlet extends jakarta.servlet.http.HttpServlet and overrides the methods for the HTTP methods it supports. The @WebServlet annotation maps it to a URL pattern, so the container finds it when it scans the application at startup.

Java
package com.example.shop;

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

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

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String name = request.getParameter("name");          // null if missing
        if (name == null || name.isBlank()) {
            name = "world";
        }
        response.setContentType("text/html;charset=UTF-8");  // before getWriter()!
        PrintWriter out = response.getWriter();
        out.println("<!doctype html>");
        out.println("<title>Hello</title>");
        out.println("<h1>Hello, " + escapeHtml(name) + "!</h1>");
    }

    private static String escapeHtml(String text) {
        return text.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;")
                   .replace("\"", "&quot;").replace("'", "&#39;");
    }
}

Deployed in shop.war, this answers GET /shop/hello?name=Ada. A few rules are visible already:

  • You never create the servlet yourself. The container instantiates it (it needs a public no-argument constructor) and calls its methods.
  • Methods you don't override are not "missing": HttpServlet's default doPost, doPut and doDelete send 405 Method Not Allowed. HEAD is handled automatically by running doGet and discarding the body, and OPTIONS lists the methods you implemented.
  • Set the content type and character encoding before calling getWriter(). The writer picks its encoding when it is created, and without charset=UTF-8 characters like รฉ or โ‚ฌ can come out garbled.
  • Escape every piece of user input you put into HTML. ?name=<script>... would otherwise run in the visitor's browser (see Web Security Basics).

The @WebServlet annotation has a few useful attributes:

Java
@WebServlet(
    name = "productApi",
    urlPatterns = {"/api/products", "/api/products/*"},
    loadOnStartup = 1,                                   // create at deployment, not on the first request
    initParams = @WebInitParam(name = "pageSize", value = "20"))
public class ProductApiServlet extends HttpServlet { ... }

Instead of annotations, servlets can also be declared in WEB-INF/web.xml, which is handy when you can't change the class or want to keep configuration in one place:

XML
<web-app xmlns="https://jakarta.ee/xml/ns/jakartaee" version="6.1">
  <servlet>
    <servlet-name>hello</servlet-name>
    <servlet-class>com.example.shop.HelloServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>hello</servlet-name>
    <url-pattern>/hello</url-pattern>
  </servlet-mapping>
</web-app>

A servlet container in miniature

The next program is the closest you can get to servlets without a real container. It defines small classes named like the real API (HttpServlet, HttpServletRequest, HttpServletResponse) with the same core methods, and a MiniContainer that does Tomcat's job: own the port, map URLs to servlet instances, build the request and response objects, and call service. Then it deploys two servlets at the context root /shop: the HelloServlet from above, and a JSON API for products.

The servlet classes at the bottom are written exactly the way you would write them against jakarta.servlet.

Java Servlets on a miniature container

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Match the output with the servlet code:

  • getParameter("name") returns the decoded value from the query string, and the <script> attempt arrives as harmless escaped text.
  • HEAD gets a 200 without a body, and POST /shop/hello gets a 405, both without any code in HelloServlet. That is the inherited behavior of HttpServlet.
  • For /api/products/*, the container sets getServletPath() to /api/products and getPathInfo() to the rest (/2), which the servlet uses as the id. Form fields from the POST body come from the same getParameter method as query parameters.
  • The POST answers 201 with a Location built from the context path and servlet path, so the servlet doesn't hard-code where it is deployed.
  • /shop/admin matches no servlet, so the container itself returns 404.

A real container adds what this sketch leaves out: request and response buffering with a configurable size, streaming output, sessions, cookies, filters, security, asynchronous processing and much more. But the contract between container and servlet is exactly this one.

The request object

HttpServletRequest gives you everything about the incoming request. The methods you will use most:

Method Returns
getMethod() "GET", "POST", ...
getRequestURI() Path including the context root, without the query: /shop/api/products/7
getContextPath() / getServletPath() / getPathInfo() The three parts of that path: /shop, /api/products, /7
getQueryString() The raw query, "sort=price&page=2", or null
getParameter(name) First value of a query or form parameter, decoded, or null
getParameterValues(name) / getParameterMap() All values (checkboxes, multi-selects)
getHeader(name) / getHeaders(name) Header values; names are case-insensitive
getCookies() / getSession() Cookies and the HTTP session (Sessions and Cookies)
getReader() / getInputStream() The raw body, for JSON or binary uploads
getRemoteAddr() The client IP (or the proxy's, behind a load balancer)
setAttribute / getAttribute Data attached to this request, for example for a JSP view

Two encoding rules prevent mysterious bugs: call request.setCharacterEncoding("UTF-8") before reading any parameter of a form POST (or configure <request-character-encoding>UTF-8</request-character-encoding> in web.xml once), and remember that getReader() and getParameter both consume the same body, so use one or the other. The next lesson, Handling Requests, Forms and Redirects, covers parameters and forms in depth.

The response object

HttpServletResponse controls what goes back:

  • setStatus(int) for normal statuses (201, 204), sendError(int, message) for errors (the container renders an error page), sendRedirect(url) for a 302 redirect.
  • setContentType("application/json"), setCharacterEncoding("UTF-8"), setHeader and addHeader for headers; addCookie for cookies.
  • getWriter() for text or getOutputStream() for binary data. Use only one of them per response; calling both throws IllegalStateException.

The response is buffered. As long as nothing has been flushed, you can still change the status and headers. Once the buffer fills or you flush it, the response is committed: status and headers are on the wire, and sendRedirect or sendError now throw IllegalStateException. Decide the status and headers first, then write the body.

A JSON endpoint on the real API looks like this. Jackson writes straight into the response writer:

Java
@WebServlet("/api/products/*")
public class ProductApiServlet extends HttpServlet {
    private final ObjectMapper json = new ObjectMapper();   // thread-safe after configuration
    private ProductRepository products;

    @Override
    public void init() {
        products = new ProductRepository((DataSource) getServletContext().getAttribute("dataSource"));
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String pathInfo = request.getPathInfo();             // null, "/" or "/{id}"
        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");
        if (pathInfo == null || pathInfo.equals("/")) {
            json.writeValue(response.getWriter(), products.findAll());
            return;
        }
        products.findById(Long.parseLong(pathInfo.substring(1))).ifPresentOrElse(
            product -> write(response, product),
            () -> response.setStatus(HttpServletResponse.SC_NOT_FOUND));
    }

    private void write(HttpServletResponse response, Object body) {
        try {
            json.writeValue(response.getWriter(), body);
        } catch (IOException e) {
            throw new UncheckedIOException(e);
        }
    }
}

Writing a whole REST API this way works, but it gets repetitive: parsing ids, mapping JSON, choosing status codes. That repetition is exactly what Jakarta REST (@Path, @GET) and Spring MVC (@RestController) remove, both running on top of servlets.

URL patterns and mapping rules

A servlet mapping uses one of four pattern types, and the container chooses in a fixed order of precedence:

  1. Exact match: /hello matches only /hello.
  2. Longest path prefix: /api/* matches /api, /api/products and /api/products/7. If both /api/* and /api/admin/* exist, the longer one wins.
  3. Extension: *.jsp or *.do matches any path ending in that extension.
  4. Default servlet: / handles everything nothing else matched (the container's own default servlet serves static files).

There is also the empty string "", which matches only the context root itself. The chosen pattern determines how the path is split into getServletPath() and getPathInfo(). This program implements the rules for a sample set of mappings:

Java How the container picks a servlet

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Note the surprising cases. /hello/extra does not reach HelloServlet, because /hello is an exact pattern; it falls through to the default servlet. /api/page.jsp goes to ApiServlet, not JspServlet, because path-prefix patterns are checked before extensions. And mapping a servlet to /* captures everything, including JSP pages and static files, which is a common mistake; front controllers such as Spring's DispatcherServlet are mapped to / instead.

One instance, many threads

The container creates one instance of each servlet (per declaration) and calls its service method from many threads at the same time: one thread per concurrent request. Instance fields are therefore shared by every request in flight. Read-only fields set in init() (configuration, an ObjectMapper, a DataSource) are fine. Mutable fields are a bug that only shows up under load.

This program reproduces what happens in a real container. A "visitor counter" servlet hands out ticket numbers from a plain int field, while 16 threads play concurrent requests. Then the same with an AtomicInteger.

Java Why mutable servlet fields are dangerous

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The unsafe version hands the same ticket number to different users, and the exact count changes from run to run: a textbook race condition (see Threads). In a real application the field could be a "current user", a StringBuilder for the response, or a shared SimpleDateFormat (which is not thread-safe either). The rules:

  • Keep request data in local variables or request attributes, never in servlet fields.
  • Shared state goes into thread-safe objects (AtomicInteger, ConcurrentHashMap), a database, or a cache.
  • Don't synchronize doGet. It makes the servlet safe by allowing only one request at a time, which turns your server into a single-user server.
  • Immutable helpers are perfect fields: a configured ObjectMapper, a DateTimeFormatter, a DataSource.

Lifecycle in brief

The container drives each servlet through three phases. init() runs once, before the first request (or at deployment with loadOnStartup); use it to read init parameters and look up shared resources. service() runs for every request, on many threads. destroy() runs once when the application is stopped or redeployed; release resources there. Configuration values from @WebInitParam or web.xml are available through getInitParameter(name), and application-wide objects through getServletContext(). Servlet Lifecycle and Deployment covers this in detail.

Java
@WebServlet(urlPatterns = "/report", loadOnStartup = 1,
            initParams = @WebInitParam(name = "maxRows", value = "500"))
public class ReportServlet extends HttpServlet {
    private int maxRows;                                   // set once, then only read: safe

    @Override
    public void init() {
        maxRows = Integer.parseInt(getInitParameter("maxRows"));
        log("ReportServlet ready, maxRows=" + maxRows);
    }

    @Override
    public void destroy() {
        log("ReportServlet stopping");
    }
}

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A servlet overrides only doGet. What does a POST request to its URL receive?

    HttpServlet's default implementations of doPost, doPut and doDelete answer 405. HEAD and OPTIONS are handled automatically.
  2. 2. With the mapping /api/* in the context /shop, what does getPathInfo() return for /shop/api/orders/12?

    The context path is /shop, the servlet path is /api, and the remainder /orders/12 is the path info.
  3. 3. Mappings /reports/* and *.pdf exist. Which servlet handles /reports/2026.pdf?

    The order is exact, then longest path prefix, then extension, then default. The path prefix wins.
  4. 4. Why is private StringBuilder html = new StringBuilder(); as a servlet field a bug?

    One instance handles all requests on many threads. Request-specific data must live in local variables.
  5. 5. A servlet writes a large body, which commits the response, and then calls response.sendRedirect("/login"). What happens?

    Once the response is committed, the status line and headers are on the wire and can't change. Decide the status before writing the body.

Summary

  • A servlet extends HttpServlet and overrides doGet, doPost, doPut or doDelete. Unimplemented methods answer 405; HEAD and OPTIONS work automatically.
  • Map servlets with @WebServlet("/path") or in web.xml. Patterns: exact, path prefix (/api/*), extension (*.jsp), default (/), checked in that order.
  • The request path splits into getContextPath(), getServletPath() and getPathInfo(); parameters from the query string and form bodies come from getParameter.
  • Set the status, headers and Content-Type with charset before writing the body; a committed response can't be changed. Use either getWriter() or getOutputStream().
  • Escape user input in HTML; write JSON with a shared ObjectMapper.
  • One servlet instance serves many threads: no mutable instance fields, no synchronized doGet; use locals, thread-safe objects or the database.
  • The container calls init() once, service() per request, and destroy() at shutdown.

Next: Handling Requests, Forms and Redirects works with parameters, HTML forms, request attributes, forward versus redirect, and file uploads.