Skip to content
Tutorials Center
My learning

Topics

Lesson 39 of 119 ยท Servlets and JSP

Servlet Lifecycle and Deployment

Learn the servlet lifecycle (init, service, destroy), why one servlet instance serves many threads, web.xml vs annotations, WAR files, Tomcat deployment and embedded servers.

You never write new MyServlet(). The servlet container (Tomcat, Jetty, WildFly and friends) creates your servlet, calls it for every matching request and destroys it when the application stops. Knowing exactly when each of those steps happens explains a lot: why a field in a servlet can corrupt data under load, why the first request after a deploy is slow, where to put setup code, and what really happens when you copy a .war file into Tomcat's webapps folder.

This lesson covers the lifecycle methods, the threading model, configuration with web.xml and annotations, the WAR format and the two ways to run a web app today: deployed into a standalone server, or with the server embedded in your own executable JAR. The servlet code is read-only here; the runnable programs simulate a container and use the JDK's HttpServer to show the same mechanics for real. The earlier lessons on servlets and filters and listeners are useful background.

The three lifecycle methods

Every servlet goes through the same stages, defined by the jakarta.servlet.Servlet interface:

  1. Loading and instantiation. The container loads the class with the web app's class loader and calls its public no-argument constructor. One instance per servlet declaration.
  2. init(ServletConfig config) is called exactly once, before the first request. This is where you read configuration and prepare expensive objects. If it throws, the servlet is not put into service.
  3. service(request, response) is called once per request, possibly by many threads at the same moment. HttpServlet.service looks at the HTTP method and calls doGet, doPost, doPut, doDelete and so on; methods you don't override answer 405 Method Not Allowed.
  4. destroy() is called exactly once, when the app is stopped, redeployed or the server shuts down, after in-flight requests have finished (or a timeout has passed). Release what init acquired.
Java
@WebServlet(urlPatterns = "/reports/*", loadOnStartup = 1,
            initParams = @WebInitParam(name = "maxRows", value = "500"))
public class ReportServlet extends HttpServlet {

    private int maxRows;                      // set once in init, then only read: safe
    private ExecutorService exportPool;       // shared resource with a clear owner

    @Override
    public void init() throws ServletException {
        try {
            maxRows = Integer.parseInt(getInitParameter("maxRows"));
        } catch (NumberFormatException e) {
            throw new ServletException("maxRows must be a number", e);
        }
        exportPool = Executors.newFixedThreadPool(4);
        log("ReportServlet ready, maxRows=" + maxRows);
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
        int page = Integer.parseInt(Objects.requireNonNullElse(request.getParameter("page"), "1"));
        // local variables belong to this request's thread only
        response.setContentType("text/plain;charset=UTF-8");
        response.getWriter().println("Report page " + page + " (max " + maxRows + " rows)");
    }

    @Override
    public void destroy() {
        exportPool.shutdown();
        log("ReportServlet stopped");
    }
}

GenericServlet (the parent of HttpServlet) stores the ServletConfig for you and offers a no-argument init() to override, which is what this example uses. If you override init(ServletConfig) instead, call super.init(config) first, or getServletConfig() and getInitParameter() will return null.

When does init run?

By default, the container creates a servlet lazily, on the first request that maps to it. That first user pays for class loading and init. With loadOnStartup (or <load-on-startup> in web.xml) set to zero or a positive number, the container initializes the servlet while deploying the app instead, lowest numbers first. Use it for servlets with slow init methods, and to find configuration errors at deploy time rather than when the first customer arrives.

The next program is a miniature container. It reads a real web.xml with the JDK's XML parser, initializes the eager servlets at deploy time, creates the lazy one on first use, matches URLs with the servlet mapping rules and destroys everything in reverse order on shutdown. One servlet has a broken init parameter so you can see what a failed init means.

Java A miniature servlet container driven by web.xml

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.

Notice four things in the output. home was initialized before products because its load-on-startup value is lower, even though it is declared second. /about has no mapping of its own, so it falls through to the default servlet /. The reports servlet is created only when /sales/2026.csv arrives, and its init fails on maxRows=lots, so the container takes it out of service instead of calling service on a half-initialized object. That failure would have shown up at deploy time if reports had a load-on-startup value. Finally, destroy runs in reverse order of initialization, and only for servlets whose init succeeded.

One instance, many threads

This is the most important fact about servlets: the container creates one instance of each servlet and calls service on it from many threads at once. Tomcat, for example, handles requests with a thread pool (200 threads by default), and every request to /reports/* runs through the same ReportServlet object.

That means:

  • Local variables are safe. Each thread has its own stack, so variables inside doGet belong to one request.
  • Instance and static fields are shared by all concurrent requests. Read-only fields set in init are fine. Mutable fields are a bug waiting for traffic.
  • Request, response and session objects are per request (or per user), but a session can still be used by two tabs at the same moment.

The classic mistake looks harmless:

Java
public class GreetingServlet extends HttpServlet {
    private String userName;                                   // shared by every request!

    protected void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException {
        userName = req.getParameter("name");                   // thread A writes "Ana"
        // ... thread B writes "Ben" here ...
        res.getWriter().println("Hello, " + userName);         // thread A prints "Hello, Ben"
    }
}

Under light testing it works. Under load, one user sees another user's data. The program below shows the same race with a counter: sixteen threads call one shared "servlet" object, as a container's pool would.

Java One servlet instance shared by 16 threads

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 LongAdder always reaches 800,000. The plain int almost always ends lower, by a different amount on every run, because two threads read the same old value and both write back "old + 1". Nothing crashes and nothing is logged; the data is silently wrong. The fixes, in order of preference:

  1. Don't share mutable state. Keep per-request data in local variables and per-user data in the session.
  2. Use thread-safe types for shared state: AtomicInteger, LongAdder, ConcurrentHashMap, immutable objects, DateTimeFormatter instead of SimpleDateFormat.
  3. Synchronize only short critical sections. A synchronized doGet makes the servlet handle one request at a time, which throws away the server's concurrency.

The old SingleThreadModel interface, which promised one thread per instance, never really solved the problem and was removed in Servlet 6.0. See Synchronization in the Java course for the underlying rules.

Thread pools, async and virtual threads

A request occupies a thread for as long as service runs. If a servlet waits two seconds for a slow API, 200 such requests use up all 200 threads and the server stops answering. There are two remedies. Async servlets (request.startAsync(), enabled with asyncSupported = true) release the container thread while waiting and finish the response later from another thread. And on Java 21+, servers can run each request on a virtual thread, which is cheap to block: Tomcat 11 offers useVirtualThreads="true" on its connector, and Spring Boot has spring.threads.virtual.enabled=true. Virtual threads change nothing about thread safety, though: shared fields are still shared.

The JDK HttpServer lets you choose its executor, which makes both models easy to see. Here the same handler object serves 40 concurrent requests, first on a pool of four platform threads, then on virtual threads.

Java The same handler on a thread pool and on virtual threads

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.

With four platform threads, the 40 requests queue up: four at a time, each sleeping 50 ms, so the batch needs at least ten rounds of 50 ms: half a second plus overhead. With virtual threads, each request gets its own cheap thread and they all wait at the same time. In both cases there is exactly one handler object. Your exact timings depend on the machine, but the gap between the two runs is what matters.

web.xml vs annotations

Since Servlet 3.0 you can configure almost everything with annotations (@WebServlet, @WebFilter, @WebListener, @MultipartConfig), and web.xml is optional. Both are still used, often together. The deployment descriptor lives at WEB-INF/web.xml:

XML
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="https://jakarta.ee/xml/ns/jakartaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="https://jakarta.ee/xml/ns/jakartaee https://jakarta.ee/xml/ns/jakartaee/web-app_6_0.xsd"
         version="6.0">

    <context-param>                              <!-- app-wide: ServletContext.getInitParameter -->
        <param-name>supportEmail</param-name>
        <param-value>[email protected]</param-value>
    </context-param>

    <servlet>
        <servlet-name>reports</servlet-name>
        <servlet-class>com.example.web.ReportServlet</servlet-class>
        <init-param>                             <!-- per servlet: ServletConfig.getInitParameter -->
            <param-name>maxRows</param-name>
            <param-value>1000</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>reports</servlet-name>
        <url-pattern>/reports/*</url-pattern>
    </servlet-mapping>

    <session-config>
        <session-timeout>30</session-timeout>
    </session-config>
</web-app>
Annotations web.xml
Where next to the code one central file
Change without recompiling no yes
Filter order undefined defined by mapping order
Error pages, session config, security constraints mostly not available yes
Good for servlets and simple filters in your own code app-wide settings, ordering, overriding library defaults

The rules for combining them: a web.xml entry with the same servlet-name as an annotated servlet overrides the annotation's values, which is handy for changing an init parameter per environment. Setting metadata-complete="true" on <web-app> tells the container not to scan for annotations at all, which also speeds up startup in large apps. Libraries can contribute their own configuration through META-INF/web-fragment.xml inside their JARs.

Two kinds of parameters are easy to confuse: <context-param> values belong to the whole application (getServletContext().getInitParameter(...)), while <init-param> values belong to one servlet or filter (getInitParameter(...) on the servlet).

The WAR file

A WAR (Web Application aRchive) is a ZIP file with a fixed layout:

TEXT
shop.war
โ”œโ”€โ”€ index.html                  โ† public static files (served directly)
โ”œโ”€โ”€ css/site.css
โ”œโ”€โ”€ META-INF/
โ”‚   โ””โ”€โ”€ MANIFEST.MF
โ””โ”€โ”€ WEB-INF/                    โ† never served to browsers
    โ”œโ”€โ”€ web.xml                 โ† optional deployment descriptor
    โ”œโ”€โ”€ classes/                โ† your compiled classes and resources
    โ”‚   โ””โ”€โ”€ com/example/web/ReportServlet.class
    โ”œโ”€โ”€ lib/                    โ† dependency JARs (Jackson, JDBC driver, ...)
    โ”‚   โ””โ”€โ”€ jackson-databind-2.22.0.jar
    โ””โ”€โ”€ views/                  โ† JSPs that only servlets may forward to
        โ””โ”€โ”€ report.jsp

Everything outside WEB-INF can be requested by a browser; nothing inside it can. That is why views go in WEB-INF/views: users can't open a JSP directly and bypass the servlet that prepares its data.

Maven builds a WAR when the packaging says so. The Servlet API is marked provided: you compile against it, but the server supplies it at run time, and bundling your own copy in WEB-INF/lib causes class-loading conflicts.

XML
<packaging>war</packaging>

<dependencies>
    <dependency>
        <groupId>jakarta.servlet</groupId>
        <artifactId>jakarta.servlet-api</artifactId>
        <version>6.1.0</version>
        <scope>provided</scope>
    </dependency>
</dependencies>

mvn package then produces target/shop.war (or whatever <finalName> says). The Maven lesson explains scopes and the build lifecycle.

Each deployed application gets its own class loader. Classes in one app's WEB-INF/classes and WEB-INF/lib are invisible to other apps on the same server, so two apps can use different versions of the same library. Unlike normal Java class loading, a web app loader looks in the app's own folders first, before the server's shared libraries (except for core Java and Servlet API classes).

Deploying to Tomcat

Pick the Tomcat version that matches your API: Tomcat 11 implements Servlet 6.1 (Jakarta EE 11), Tomcat 10.1 implements Servlet 6.0 (Jakarta EE 10), and Tomcat 9 is the last version using the old javax.servlet packages. A WAR built against jakarta.servlet will not run on Tomcat 9, and vice versa; the Jakarta EE overview explains the rename.

Terminal
# Start Tomcat in the foreground, logs in the terminal (Ctrl+C stops it)
$CATALINA_HOME/bin/catalina.sh run          # Windows: catalina.bat run

# Deploy: copy the WAR into webapps; the file name becomes the context path
cp target/shop.war $CATALINA_BASE/webapps/   # -> http://localhost:8080/shop/
cp target/shop.war $CATALINA_BASE/webapps/ROOT.war   # -> http://localhost:8080/

# Undeploy: delete the WAR (Tomcat removes the unpacked folder too)
rm $CATALINA_BASE/webapps/shop.war

With the default autoDeploy="true", Tomcat watches webapps: a new WAR is unpacked and started, a replaced WAR triggers a redeploy (old app's destroy methods run, then the new app's init), and a deleted WAR is undeployed. Logs go to logs/catalina.out (or the console) and logs/localhost.<date>.log; a failed deployment almost always explains itself there. Tomcat's Manager web app and its text interface (/manager/text/deploy) let scripts deploy remotely, but in production most teams now build an immutable image instead of hot-deploying.

Repeated hot redeploys in one Tomcat process can leak memory: if anything outside the app (a JDBC driver registration, a thread you started, a ThreadLocal) still references the old app's class loader, none of its classes can be garbage collected. Tomcat logs warnings about these leaks. Close what you open in destroy and contextDestroyed, and restart the server occasionally instead of redeploying forever.

Embedded servers

The traditional model is "one server, many WARs". The modern default flips it: your application contains the server. You build one executable JAR that starts an embedded Tomcat, Jetty or Undertow inside main, and you run it with java -jar app.jar. Spring Boot does this out of the box, and it is how most new Java web services ship, usually inside a Docker container.

Java
import org.apache.catalina.Context;
import org.apache.catalina.startup.Tomcat;

public class Main {
    public static void main(String[] args) throws Exception {
        Tomcat tomcat = new Tomcat();
        tomcat.setPort(8080);
        tomcat.getConnector();                               // create the default HTTP connector

        Context ctx = tomcat.addContext("", null);           // context path "" = root, no docBase
        Tomcat.addServlet(ctx, "reports", new ReportServlet());
        ctx.addServletMappingDecoded("/reports/*", "reports");

        tomcat.start();                                      // init() of load-on-startup servlets runs here
        tomcat.getServer().await();                          // block until shutdown
    }
}

The servlets are the same; only who owns main changes. The trade-offs:

Standalone server + WAR Embedded server in a JAR
Server version chosen by operations, shared by apps chosen by the app, in its dependencies
Deploy copy a WAR, hot redeploy start a new process or container
Isolation apps share a JVM and memory one app per JVM
Configuration server.xml, context.xml code or application properties
Typical today existing enterprise apps, app servers Spring Boot, microservices, containers

Either way, shut down gracefully: stop accepting new connections, let running requests finish, then call destroy. Embedded servers usually do this from a JVM shutdown hook when the process receives SIGTERM, which is what Docker and Kubernetes send.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A servlet has no loadOnStartup setting. When does the container call its init method?

    Without load-on-startup, servlets are created lazily, so the first matching request triggers class loading, instantiation and init.
  2. 2. How many instances of a servlet declared once does the container normally create, and how many threads can call it at the same time?

    The container keeps a single instance per declaration and calls service concurrently from its request threads, so mutable fields are shared.
  3. 3. Which field in a servlet is safe without synchronization?

    Immutable or read-only objects can be shared freely. The other fields are written or internally modified by concurrent requests.
  4. 4. Where should a JSP go so that users can't open it directly in the browser?

    The container never serves files under WEB-INF to clients, but servlets can still forward to them.
  5. 5. Why is the Servlet API dependency marked provided in a WAR project?

    You compile against the API, but the container has its own implementation. A second copy in the WAR causes class-loading conflicts.

Summary

  • The container instantiates a servlet, calls init once, service once per request (dispatching to doGet, doPost, ...) and destroy once at shutdown.
  • Servlets are created on the first request unless loadOnStartup is zero or more; lower values start first. A failing init keeps the servlet out of service.
  • One instance serves many threads. Keep request data in local variables, make shared fields read-only or thread-safe, and avoid synchronizing whole methods.
  • Async servlets and virtual threads keep slow requests from exhausting the thread pool; they don't make shared state safe.
  • Configure with annotations, web.xml or both; web.xml wins for the same servlet name and is required for defined filter order, error pages and similar settings.
  • A WAR has public files at the root and private files in WEB-INF (web.xml, classes, lib). Mark the Servlet API provided.
  • Deploy to Tomcat by copying the WAR to webapps (match Tomcat 10.1+/11 with jakarta.*), or embed the server and ship an executable JAR, as Spring Boot does.

Next: JavaServer Pages (JSP) shows how to write HTML views that servlets forward to, and how JSP turns them into servlets behind the scenes.