Single logo
  • Courses
  • Blog
  • About
Join on SkoolJoin on Skool

In this topic

JSP and Servlets
  • Servlets and JSP: What a Servlet Container Does and How a JSP Becomes a Servlet
  • Set Up Tomcat 11 and a Maven Web Project in IntelliJ IDEA
  • The Servlet Request Lifecycle: @WebServlet, web.xml, init, doGet and destroy
  • Servlet Request Parameters, and Forward vs Redirect
  • Run a Java Web App in Docker: Tomcat 11 With One Compose Command
  • Sessions, Cookies and Filters in Java Servlets: Log In Once, Stay Logged In
  • Servlets and JSP: What a Servlet Container Does and How a JSP Becomes a Servlet
  • JSP Scripting: Expressions, Scriptlets, Declarations, Comments and Includes
  • JavaBeans and JSP Scopes: Page, Request, Session and Application
  • JSP Expression Language Step by Step: ${...} for Beans, Maps, Lists, Params and Scopes
  • JSTL Core Tags: c:set, c:out, c:if, c:choose and c:forEach
  • JSTL Functions and Formatting: fn:length, fn:toUpperCase, fn:contains, fmt:formatNumber and fmt:formatDate
  • Maintaining and Migrating Legacy JSP With AI: Explain the Page, Refactor to a DAO, Servlet and JSTL, Then Move It to React
  • MVC and the Front Controller With Servlets and JSP
  • Forms With JSP and Servlets: Handle the POST and Validate on the Server
  • Mini App With Servlets and JSP: Login, Logout and a Shared Web Template
  • SQLite and a JDBC Connection Pool in a Java Web App
  • Users CRUD With Servlets and JSP, Part 1: Add and List Through a DAO
  • Users CRUD With Servlets and JSP, Part 2: Update and Delete
  1. Blog
  2. /
  3. JSP and Servlets
  4. /
  5. Servlets

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.

Chaand Sheikh

·27 November 2026·Updated 28 November 2026Servlets

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.

  1. The browser sends GET /hello.
  2. Tomcat looks up /hello in its URL map and finds HelloServlet.
  3. Tomcat creates two objects for this request, req and resp, and calls doGet(req, resp).
  4. Our code writes HTML into resp.
  5. Tomcat sends it back as 200 OK and the page shows up.
The browser sends GET /hello to Tomcat. Tomcat finds HelloServlet in its URL map and calls doGet with req and resp. The servlet writes HTML into resp, and Tomcat returns 200 OK with the finished page. Browser draws the page Tomcat URL map /hello → HelloServlet makes req + resp HelloServlet doGet(req, resp) GET /hello calls doGet HTML in resp 200 OK The browser never sees Java. It receives finished HTML.
One GET request: Tomcat maps the URL to a class and calls doGet with a fresh req and resp.

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.
  • doGet runs 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(), then doGet(). visits becomes 1.
  • On the second and third requests there is no new object and no init(). The same object runs doGet() again, so visits reaches 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.

Timeline of one servlet object: init runs once at the first request, doGet runs for requests one, two and three with visits counting 1, 2, 3, and destroy runs once when Tomcat stops. init()once doGet()visits = 1 doGet()visits = 2 doGet()visits = 3 destroy()once 1st request Tomcat stops one object for every request
The life of LifecycleServlet: one object, one init, a doGet per request, one destroy.

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 reports Invalid <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. visits is 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

PieceWhat it does
@WebServlet("/hello")Maps a URL to the class, on the class itself
web.xmlMaps 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.

Tried the exercise? Share your answer or ask a question.

The StudyEasy AI Community is free to join, with the lesson files, notebooks and code.

Join free on Skool

Keep going in JSP and Servlets · 3 of 19

Previous
Set Up Tomcat 11 and a Maven Web Project in IntelliJ IDEA
Next post
Servlet Request Parameters, and Forward vs Redirect

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.

On this page

  • One request, start to finish
  • A class that answers a URL
  • Plain Java data in the page
  • Mapping in web.xml
  • init, doGet and destroy
  • A JSP is a servlet too
  • Common mistakes
  • Quick recap
  • Try it yourself
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

Learn AI engineering, share what you build, and connect with other learners.

  • Free resources: lesson files, notebooks and code

  • Ask questions and join engineering discussions

  • Meet real people learning and building with AI

Join free on Skool

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)

Single logo

Empowering Education, One Course at a Time

About
About usContact us
Legal
Terms of UsePrivacy Policy

© 2026 StudyEasy Organization. All rights reserved.