The Servlet Request Lifecycle: @WebServlet, web.xml, init, doGet and destroy
A servlet is a Java class that answers a URL. Follow one request through Tomcat, map servlets with @WebServlet and web.xml, build a page from a list, and watch init, doGet and destroy run.
What you will learn
- Follow one GET request from the browser through Tomcat to a servlet and back
- Map a servlet to a URL with @WebServlet or with web.xml
- Build an HTML page from a Java list inside doGet
- Explain why init and destroy run once while doGet runs on every request
Before you start
- Java classes and methods
- A Tomcat 11 web project you can run
A servlet is a Java class that answers a URL. The browser asks for /hello, Tomcat finds the class that owns that address, calls one method on it, and the method writes the HTML. The browser gets a finished page and only has to draw it.
In this article we build three small servlets in the org.studyeasy.web package: one with a fixed page, one that builds a page from a list, and one that shows the lifecycle.
One request, start to finish
There are three players: the browser, Tomcat with its URL map, and our servlet.
- The browser sends
GET /hello. - Tomcat looks up
/helloin its URL map and findsHelloServlet. - Tomcat creates two objects for this request,
reqandresp, and callsdoGet(req, resp). - Our code writes HTML into
resp. - Tomcat sends it back as
200 OKand the page shows up.
A class that answers a URL
Here is the whole servlet:
package org.studyeasy.web;
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;
// Tomcat sends every request for /hello to this class
@WebServlet("/hello")
public class HelloServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws IOException {
// tell the browser the answer is an HTML page
resp.setContentType("text/html");
PrintWriter out = resp.getWriter();
out.println("<h1>Hello from a servlet</h1>");
out.println("<p>Java built this page on the server.</p>");
}
}
Line by line:
@WebServlet("/hello")tells Tomcat that this class answers/hello.doGetruns for every GET request. It always takes the request and the response, so this signature looks the same in every servlet you write.setContentType("text/html")tells the browser the answer is an HTML page.out.println(...)writes ordinary HTML into the response.
Open /hello and the browser shows:
Hello from a servlet
Java built this page on the server.
Watch the two kinds of println. out.println writes into the response, so it goes to the browser. System.out.println writes to the console, so it shows up in the Tomcat log. Same word, two very different places.
You don't need to memorise this boilerplate. A one-line prompt such as "Write a Jakarta servlet mapped to /hello that prints a heading and a paragraph" gets an AI assistant to write it. What you do need is to read it and know what each line is for.
Plain Java data in the page
A servlet is just Java, so the page can come from any data you have. This one prints a list of tasks:
package org.studyeasy.web;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
// No annotation: WEB-INF/web.xml maps this class to /tasks
public class TasksServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws IOException {
List<String> tasks =
List.of("Write the report", "Book a room", "Email Olivia");
resp.setContentType("text/html");
PrintWriter out = resp.getWriter();
out.println("<h1>Today's tasks</h1>");
out.println("<ul>");
// one <li> per task: Java builds the page
for (String task : tasks) {
out.println("<li>" + task + "</li>");
}
out.println("</ul>");
}
}
The for loop runs three times and writes one <li> per pass: "Write the report", then "Book a room", then "Email Olivia". The browser shows:
Today's tasks
* Write the report
* Book a room
* Email Olivia
Inside a servlet you have all of Java: lists, loops, a database call, your own logic. That is the whole point of running code on the server.
Mapping in web.xml
Look at the top of TasksServlet again. There's no @WebServlet. So how does Tomcat know it answers /tasks? The mapping lives in src/main/webapp/WEB-INF/web.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_1.xsd"
version="6.1">
<!-- the same job as @WebServlet, written in XML -->
<servlet>
<servlet-name>tasks</servlet-name>
<servlet-class>org.studyeasy.web.TasksServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>tasks</servlet-name>
<url-pattern>/tasks</url-pattern>
</servlet-mapping>
</web-app>
The <servlet> block gives the class a name, tasks. The <servlet-mapping> block connects that name to the URL /tasks.
Both ways fill the same URL map when the app starts. The annotation puts /hello in it, and web.xml puts /tasks in it. The annotation is easier to work with because the URL sits right on the class. Use @WebServlet for new code, and be ready to read web.xml when an older app already has one.
init, doGet and destroy
A servlet has three lifecycle methods worth knowing:
package org.studyeasy.web;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebServlet("/lifecycle")
public class LifecycleServlet extends HttpServlet {
private int visits = 0; // one object serves every request
@Override
public void init() {
System.out.println("init(): servlet object created");
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws IOException {
visits++;
System.out.println("doGet(): request " + visits);
resp.setContentType("text/html");
resp.getWriter().println("<h1>Visit number " + visits + "</h1>");
}
@Override
public void destroy() {
System.out.println("destroy(): server shutting down");
}
}
Open /lifecycle three times, then stop Tomcat. The Tomcat log shows:
init(): servlet object created
doGet(): request 1
doGet(): request 2
doGet(): request 3
destroy(): server shutting down
Here is what happened:
- On the first request, Tomcat creates the object and calls
init(), thendoGet().visitsbecomes 1. - On the second and third requests there is no new object and no
init(). The same object runsdoGet()again, sovisitsreaches 3. - When Tomcat stops,
destroy()runs once and the object is gone.
That's why the visits field keeps counting between requests: there is one servlet object, and every request goes through it.
A JSP is a servlet too
What if the request is for hello.jsp instead? Behind the scenes Tomcat writes a servlet from the JSP (a file called hello_jsp.java), compiles it and makes one object. It lives the same life: jspInit once, _jspService on every request, jspDestroy once, and it gets its own req and resp. More on that in Servlets and JSP: what Tomcat does for you.
Common mistakes
- Leaving out the leading slash. Write
@WebServlet("hello")and the app does not start. Tomcat reportsInvalid <url-pattern> [hello] in servlet mapping. It must be"/hello". - Printing with System.out and expecting it in the page. That text goes to the Tomcat log. Use the writer from
resp.getWriter(). - Treating a field as per-user data.
visitsis shared by every visitor because there is only one servlet object. Per-user data belongs in the session. - Mapping the same URL twice. If an annotation and web.xml both claim one URL, you've written the same job in two places. Pick one.
Quick recap
| Piece | What it does |
|---|---|
@WebServlet("/hello") | Maps a URL to the class, on the class itself |
web.xml | Maps a URL to a class in XML, inside WEB-INF |
doGet(req, resp) | Runs on every GET request and writes the answer |
init() / destroy() | Run once, when the object is created and when Tomcat stops |
Try it yourself
Add a fourth task to the list in TasksServlet and reload /tasks. Then add a System.out.println inside the loop and check where that text shows up.
Related course on Udemy
FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE
Java 25, JSP, Hibernate, Spring Boot 4, REST APIs, React and Spring AI.View on Udemy ↗: FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE (paid course, opens in a new tab)Related posts
Servlets and JSP: What a Servlet Container Does and How a JSP Becomes a Servlet
A JSP looks like HTML with a little Java, yet Tomcat runs it as a servlet. See what a servlet container does for each request, what the generated hello_jsp.java looks like, what a .war holds, and Tomcat vs TomEE.
Set Up Tomcat 11 and a Maven Web Project in IntelliJ IDEA
Set JAVA_HOME, install Tomcat 11 on a free port, create a Jakarta EE web application with Maven in IntelliJ IDEA, read its folders and pom.xml, and run it on Tomcat.
Servlet Request Parameters, and Forward vs Redirect
Read ?name=Emma with getParameter, then hand a request on two ways: a forward keeps one request and its attributes, a redirect makes the browser ask again and the attribute is gone.
Run a Java Web App in Docker: Tomcat 11 With One Compose Command
Run a servlet project without installing Tomcat: one docker compose command builds the WAR with Maven on Java 25, starts Tomcat 11 in a container, and serves the app on localhost:8090.
