Java Servlet Basics

Su Suriya Ravichandran Updated 18 Nov 2026
10 min read ·Lesson 268 of 306

A Java servlet is a class that runs inside a web container, such as Apache Tomcat, and answers HTTP requests. The container handles sockets, threads and HTTP parsing; your servlet only reads the request and writes the response. Servlets are the foundation of Java web development: JSP, Jakarta REST and Spring MVC all run on top of them.

This lesson writes your first servlet, maps it to URLs, handles GET and POST, sends HTML and JSON, and finishes with a small course API. It uses the student-portal project and Tomcat 11 setup from Build WAR File in Java.


How a Java Servlet Handles a Request

When a request arrives, the container picks a servlet by URL, creates request and response objects, and calls the servlet's method on a worker thread.

Browser ── GET /student-portal/hello ──► Tomcat
                                           │ 1. find the app by context path (/student-portal)
                                           │ 2. find the servlet by URL pattern  (/hello)
                                           │ 3. build HttpServletRequest + HttpServletResponse
                                           ▼
                                   HelloServlet.doGet(request, response)
                                           │ 4. your code writes the response
Browser ◄──────── 200 OK + body ───────────┘
ObjectTypeUse it to
RequestHttpServletRequestRead parameters, headers, cookies and the body
ResponseHttpServletResponseSet the status, headers and content type, and write the body
ContainerTomcat, Jetty, GlassFishRun servlets, manage threads and sessions

How it works:

  • Every concept from HTTP Basics in Java maps to a method: request.getMethod(), request.getHeader(...), response.setStatus(...) and so on.
  • Tomcat 10 and later use the jakarta.servlet package. Code that imports javax.servlet belongs to Tomcat 9 or older and will not load on Tomcat 11.

Set Up a Servlet Project

The only dependency you need is the Servlet API with provided scope, because Tomcat supplies it at run time.

<packaging>war</packaging>

<dependencies>
  <dependency>
    <groupId>jakarta.servlet</groupId>
    <artifactId>jakarta.servlet-api</artifactId>
    <version>6.1.0</version>
    <scope>provided</scope>
  </dependency>
</dependencies>
Tomcat versionServlet APIPackageMinimum Java
9.04.0javax.servlet8
10.16.0jakarta.servlet11
11.06.1jakarta.servlet17

How it works:

  • jakarta.servlet-api 6.1.0 matches Tomcat 11. Compiling against a newer API than the server supports can cause NoSuchMethodError at run time.
  • Build with mvn package and copy target/student-portal.war to Tomcat's webapps folder.

Write Your First Java Servlet

Extend HttpServlet and override the method for the HTTP method you want to handle.

package com.gocourse.portal;

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;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;

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

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws IOException {
        response.setContentType("text/plain;charset=UTF-8");   // set before getWriter()
        PrintWriter out = response.getWriter();
        out.println("Hello from a Java servlet!");
        out.println("Server time: " + LocalTime.now().format(DateTimeFormatter.ofPattern("HH:mm")));
    }
}
mvn -q package && cp target/student-portal.war $CATALINA_HOME/webapps/
curl -i http://localhost:8080/student-portal/hello

Output (Date header removed):

HTTP/1.1 200 
Content-Type: text/plain;charset=UTF-8
Content-Length: 46

Hello from a Java servlet!
Server time: 14:05

How it works:

  • @WebServlet("/hello") registers the class with the container, so no XML is needed.
  • setContentType must come before getWriter(). The writer uses the charset from the content type; set it later and the text may be encoded as ISO-8859-1.
  • The status is 200 by default. Tomcat sends no reason phrase (OK) after the code, which HTTP/1.1 allows.
  • The full URL is the context path (/student-portal) plus the servlet pattern (/hello).

HttpServlet Methods: doGet, doPost and More

HttpServlet.service() reads the request method and calls the matching doXxx method.

MethodCalled forDefault behaviour if not overridden
doGetGET405 Method Not Allowed
doPostPOST405 Method Not Allowed
doPutPUT405 Method Not Allowed
doDeleteDELETE405 Method Not Allowed
doPatchPATCH (Servlet 6.1)405 Method Not Allowed
doHeadHEADRuns doGet and drops the body
doOptionsOPTIONSLists the overridden methods in Allow

HelloServlet overrides only doGet. Try other methods:

curl -s -o /dev/null -w "%{http_code}\n" -X POST http://localhost:8080/student-portal/hello
curl -s -i -X OPTIONS http://localhost:8080/student-portal/hello | grep Allow

Output:

405
Allow: GET, HEAD, OPTIONS

How it works:

  • A POST reaches the inherited doPost, which sends 405.
  • doOptions inspects which methods your class overrides and builds the Allow header automatically. HEAD comes free with GET. Some containers also list TRACE when it is enabled.
  • Override service() only in rare cases; doing so skips this method dispatch.

Map a Servlet to URLs

@WebServlet accepts one or more URL patterns. The container supports four kinds.

PatternExampleMatches
Exact/helloOnly /hello
Path prefix/courses/*/courses, /courses/7, /courses/7/lessons
Extension*.report/sales.report, /a/b/x.report
Default/Anything no other servlet matches

When several patterns match, the container picks in this order: exact match, then the longest path prefix, then extension, then default.

@WebServlet(name = "CourseInfoServlet", urlPatterns = {"/courses", "/courses/*"})
public class CourseInfoServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws IOException {
        response.setContentType("text/plain;charset=UTF-8");
        PrintWriter out = response.getWriter();
        out.println("servletPath = " + request.getServletPath());
        out.println("pathInfo    = " + request.getPathInfo());
    }
}
curl http://localhost:8080/student-portal/courses
curl http://localhost:8080/student-portal/courses/java/lessons

Output:

servletPath = /courses
pathInfo    = null
servletPath = /courses
pathInfo    = /java/lessons

How it works:

  • urlPatterns takes an array, so one servlet can serve several URLs.
  • getServletPath() returns the part that matched the pattern, and getPathInfo() returns the rest. REST-style servlets read IDs from pathInfo.
  • name gives the servlet a name that appears in logs and can be referenced from web.xml.

Handle an HTML Form With doPost

Forms send their fields in the request body. request.getParameter() reads them the same way it reads query-string values.

<!-- src/main/webapp/register.html -->
<form method="post" action="register">
  <label>Name <input name="studentName"></label>
  <label>Course
    <select name="course">
      <option>Java</option>
      <option>Python</option>
    </select>
  </label>
  <button type="submit">Register</button>
</form>
@WebServlet("/register")
public class RegisterServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws IOException {
        request.setCharacterEncoding("UTF-8");      // read non-English names correctly
        String studentName = request.getParameter("studentName");
        String course = request.getParameter("course");

        if (studentName == null || studentName.isBlank()) {
            response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Name is required");
            return;
        }

        response.setContentType("text/html;charset=UTF-8");
        response.getWriter().printf(
                "<h1>Welcome, %s!</h1><p>You joined the %s course.</p>%n",
                escapeHtml(studentName), escapeHtml(course));
    }

    private static String escapeHtml(String text) {
        return text.replace("&", "&").replace("<", "<")
                   .replace(">", ">").replace("\"", """);
    }
}
curl -d "studentName=Asha&course=Java" http://localhost:8080/student-portal/register
curl -s -o /dev/null -w "%{http_code}\n" -d "course=Java" http://localhost:8080/student-portal/register
curl -d "studentName=<b>Ravi</b>&course=Python" http://localhost:8080/student-portal/register

Output:

<h1>Welcome, Asha!</h1><p>You joined the Java course.</p>
400
<h1>Welcome, <b>Ravi</b>!</h1><p>You joined the Python course.</p>

How it works:

  • The form's action="register" is relative, so the browser posts to /student-portal/register.
  • setCharacterEncoding("UTF-8") must run before the first getParameter call; otherwise the container decodes the body with its default charset.
  • sendError(400, ...) sets the status and makes Tomcat return its error page.
  • escapeHtml turns <b> into harmless text. Writing user input into HTML without escaping allows cross-site scripting (XSS).

Send JSON From a Servlet

For APIs, set the content type to application/json and write a JSON string. A library such as Gson converts Java objects for you.

<dependency>
  <groupId>com.google.code.gson</groupId>
  <artifactId>gson</artifactId>
  <version>2.13.2</version>
</dependency>
@WebServlet("/api/profile")
public class ProfileServlet extends HttpServlet {

    record Profile(String name, String course, int marks) {}

    private static final Gson GSON = new Gson();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws IOException {
        Profile profile = new Profile("Asha", "Java", 92);
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().write(GSON.toJson(profile));
    }
}
curl http://localhost:8080/student-portal/api/profile

Output:

{"name":"Asha","course":"Java","marks":92}

How it works:

  • Gson 2.10 and later serialize Java records directly, using the record component names as JSON keys.
  • Gson objects are thread-safe, so one static final instance can be shared by all requests.
  • Gson has compile scope, so the build copies it into WEB-INF/lib.

Map Servlets With web.xml

Before annotations, every servlet was declared in WEB-INF/web.xml. It is still useful when you cannot change the class, or want all mappings in one file.

<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">

  <servlet>
    <servlet-name>greeting</servlet-name>
    <servlet-class>com.gocourse.portal.GreetingServlet</servlet-class>
  </servlet>

  <servlet-mapping>
    <servlet-name>greeting</servlet-name>
    <url-pattern>/greet</url-pattern>
    <url-pattern>/welcome</url-pattern>
  </servlet-mapping>

  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
  </welcome-file-list>
</web-app>
public class GreetingServlet extends HttpServlet {   // no @WebServlet here
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws IOException {
        response.setContentType("text/plain;charset=UTF-8");
        response.getWriter().println("Greetings via " + request.getServletPath());
    }
}
curl http://localhost:8080/student-portal/greet
curl http://localhost:8080/student-portal/welcome

Output:

Greetings via /greet
Greetings via /welcome
@WebServletweb.xml
WhereOn the classOne XML file
Change mapping without recompilingNoYes
Good forMost new appsThird-party servlets, central config

How it works:

  • <servlet> declares a name and class; <servlet-mapping> connects the name to one or more patterns.
  • welcome-file-list serves index.html when a user opens the app's root URL.
  • If both declare the same servlet name, web.xml wins, which lets you override an annotation at deploy time.

Real-World Example: Java Servlet for a Course API

This servlet is a small REST API for courses. It lists all courses, returns one by ID, creates a course from a JSON body and deletes a course, using proper status codes for each case.

// src/main/java/com/gocourse/portal/CourseApiServlet.java
package com.gocourse.portal;

import com.google.gson.Gson;
import com.google.gson.JsonParseException;
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.util.Map;
import java.util.concurrent.ConcurrentSkipListMap;
import java.util.concurrent.atomic.AtomicInteger;

@WebServlet("/api/courses/*")
public class CourseApiServlet extends HttpServlet {

    record Course(int id, String title, int lessons) {}
    record NewCourse(String title, int lessons) {}
    record ApiError(String error) {}

    private static final Gson GSON = new Gson();
    private final Map<Integer, Course> courses = new ConcurrentSkipListMap<>();  // sorted by id
    private final AtomicInteger nextId = new AtomicInteger(1);

    public CourseApiServlet() {
        addCourse("Java Tutorial", 306);
        addCourse("Python Tutorial", 120);
    }

    private static final int NO_ID = 0;      // /api/courses
    private static final int BAD_ID = -1;    // /api/courses/abc

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws IOException {
        int id = parseId(request.getPathInfo());
        if (id == BAD_ID) {
            writeJson(response, 400, new ApiError("Course id must be a number"));
            return;
        }
        if (id == NO_ID) {
            writeJson(response, 200, courses.values());
            return;
        }
        Course course = courses.get(id);
        if (course == null) {
            writeJson(response, 404, new ApiError("Course " + id + " not found"));
        } else {
            writeJson(response, 200, course);
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws IOException {
        NewCourse input;
        try {
            input = GSON.fromJson(request.getReader(), NewCourse.class);
        } catch (JsonParseException e) {
            writeJson(response, 400, new ApiError("Body is not valid JSON"));
            return;
        }
        if (input == null || input.title() == null || input.title().isBlank() || input.lessons() <= 0) {
            writeJson(response, 400, new ApiError("title and a positive lessons count are required"));
            return;
        }
        Course created = addCourse(input.title(), input.lessons());
        response.setHeader("Location", request.getContextPath() + "/api/courses/" + created.id());
        writeJson(response, 201, created);
    }

    @Override
    protected void doDelete(HttpServletRequest request, HttpServletResponse response)
            throws IOException {
        int id = parseId(request.getPathInfo());
        if (id == BAD_ID || id == NO_ID) {
            writeJson(response, 400, new ApiError("DELETE needs a numeric course id"));
            return;
        }
        if (courses.remove(id) == null) {
            writeJson(response, 404, new ApiError("Course " + id + " not found"));
        } else {
            response.setStatus(HttpServletResponse.SC_NO_CONTENT);   // 204, no body
        }
    }

    private Course addCourse(String title, int lessons) {
        Course course = new Course(nextId.getAndIncrement(), title, lessons);
        courses.put(course.id(), course);
        return course;
    }

    /** Reads the id from pathInfo: null or "/" gives NO_ID, "/7" gives 7, "/abc" gives BAD_ID. */
    private static int parseId(String pathInfo) {
        if (pathInfo == null || pathInfo.equals("/")) {
            return NO_ID;
        }
        try {
            int id = Integer.parseInt(pathInfo.substring(1));
            return id > 0 ? id : BAD_ID;
        } catch (NumberFormatException e) {
            return BAD_ID;
        }
    }

    private static void writeJson(HttpServletResponse response, int status, Object body)
            throws IOException {
        response.setStatus(status);
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().write(GSON.toJson(body));
    }
}
BASE=http://localhost:8080/student-portal/api/courses
curl -s $BASE; echo
curl -s $BASE/2; echo
curl -s -i -H "Content-Type: application/json" -d '{"title":"Go Language","lessons":90}' $BASE | grep -E "HTTP|Location|\{"
curl -s -w " (%{http_code})\n" $BASE/abc
curl -s -w " (%{http_code})\n" -d '{"title":""}' $BASE
curl -s -o /dev/null -w "%{http_code}\n" -X DELETE $BASE/1
curl -s -w " (%{http_code})\n" $BASE/1

Output:

[{"id":1,"title":"Java Tutorial","lessons":306},{"id":2,"title":"Python Tutorial","lessons":120}]
{"id":2,"title":"Python Tutorial","lessons":120}
HTTP/1.1 201 
Location: /student-portal/api/courses/3
{"id":3,"title":"Go Language","lessons":90}
{"error":"Course id must be a number"} (400)
{"error":"title and a positive lessons count are required"} (400)
204
{"error":"Course 1 not found"} (404)

How it works:

  1. One servlet, one resource. The pattern /api/courses/* sends both /api/courses and /api/courses/7 to this class. getPathInfo() tells them apart.
  2. Method per action. doGet reads, doPost creates and doDelete removes. PUT and PATCH are not overridden, so the container answers them with 405.
  3. JSON in and out. request.getReader() streams the body straight into Gson, and writeJson sets the status and content type before writing.
  4. Clear errors. Bad IDs and bad bodies return 400, unknown IDs return 404, and successful creates return 201 with a Location header.
  5. Thread safety. The container creates one instance of the servlet and calls it from many threads at once, so the data uses ConcurrentSkipListMap and AtomicInteger. Why there is only one instance, and when it is created and destroyed, is explained in Servlet Lifecycle in Java. Reading every part of the request is covered in HttpServletRequest in Java.

0 Comments

Reviewed before they appear

No comments yet.

Java
Java Introduction Java Features Java Syntax Java Comments Java Statements Java Output Java Variables Java Data Types Java Type Casting Java Operators Java Strings Java Numbers Java Math Java Booleans Java User Input Java Conditions Java If Else Java Switch Java While Loop Java For Loop Java Break Java Continue Java Arrays Java Methods Java Parameters Java Return Values Java Scope Java Recursion Install Java Install JDK Java IDEs Java JDK Java JRE Java JVM Java Compiler Java File Compile Java Run Java JShell Basics Java Packages Java OOP Java Classes Java Objects Class Methods Constructors Constructor Overload this Keyword static Keyword final Keyword Encapsulation Inheritance Polymorphism Abstraction Access Modifiers super Keyword Method Overload Method Override Instanceof Operator Nested Classes Inner Classes Anonymous Classes Enums Records Array Basics Array Length Loop Arrays Multidimensional Arrays Array Copy Array Sorting Array Search ArrayList LinkedList HashSet TreeSet HashMap TreeMap Queue Interface Deque Interface Stack Class Iterator List Interface Set Interface Map Interface Collections Class Comparable Comparator Generics Basics Generic Classes Generic Methods Wildcards String Basics String Length String Methods String Concatenation String Compare String Search String Replace String Split String Format StringBuilder StringBuffer Text Blocks Regular Expressions Number Types Integer Class Float Class Double Class BigInteger BigDecimal Math Class Random Numbers Number Format Date Basics LocalDate LocalTime LocalDateTime ZonedDateTime Date Formatting Date Parsing Period Class Duration Class Java Instant Class Java Exception Basics Java try...catch Java Multiple Catch Blocks Java finally Block Java throw Keyword Java throws Keyword Java Checked Exceptions Java Unchecked Exceptions Java Custom Exceptions Java try-with-resources Java Exception Chaining Java File Basics Java Create Files Java Read Files Java Write Files Java Delete Files Java File Paths Java File Class Java BufferedReader Java BufferedWriter Java FileInputStream Java FileOutputStream Java Object Streams Java Directory Handling Java NIO Basics Java Files API Java Input Java Scanner Class Java Console Input Java PrintStream Java InputStream Java OutputStream Java Reader Class Java Writer Class Java Buffered Streams Java Data Streams Java Generics Introduction Java Generic Types Java Generic Methods Java Bounded Types Java Wildcards Java Type Erasure Java Generic Interfaces Java Generic Collections Java Lambda Basics Java Lambda Syntax Java Functional Interfaces Java Method References Java Stream API Java Stream Creation Java Stream Filter Java Stream Map Java Stream Reduce Java Stream Sort Java Stream Collect Java Collectors Class Java Optional Class Java Parallel Streams Java Threads: Thread Basics Create a Thread in Java Java Thread Class Java Runnable Interface Java Thread States Java Thread Sleep Java Thread Join Java Thread Priority Java Synchronization Java Thread Safety Java Race Conditions Java Deadlocks Java Executor Service Java Thread Pools Java Callable Interface Java Future Interface Java CompletableFuture Java Concurrent Collections Java Atomic Classes Java Virtual Threads Java Networking Basics Java URL Class Java URI Class Java HttpClient Java HTTP Requests Java HTTP Responses Java Socket Basics Java ServerSocket Java DatagramSocket Java WebSocket Basics Java JDBC Basics Java JDBC Setup Java Database Connection Java JDBC Connection Interface Java JDBC Statement Java PreparedStatement Java ResultSet Java JDBC CRUD Operations Java JDBC Transactions Java JDBC Batch Update Java Connection Pooling with HikariCP Java JPA Basics: Entities, EntityManager and JPQL Java Hibernate Basics: SessionFactory, Session and HQL Package in Java: Basics Explained with Examples Create Package in Java: Step-by-Step Guide with Examples Import Package in Java: The import Statement Explained Access Control in Java: Packages, Classes and Members JAR File in Java: Create, Run and Inspect JAR Files Java Modules: Introduction to the Java Module System module-info in Java: Every Module Directive Explained Java Module Path: How --module-path Finds Your Modules Java Classpath: How -cp and CLASSPATH Find Your Classes Java Annotations: Basics of @ Metadata in Java Java Built-in Annotations: @Override, @Deprecated and More Java Custom Annotations: Create Your Own @interface Java Annotation Targets: @Target and ElementType Explained Java Reflection API: Inspect and Use Classes at Runtime Java Class Metadata: Names, Modifiers, Hierarchy and Generic Java Dynamic Objects: Create Objects Dynamically With Reflec Java Dynamic Proxy: Intercept Method Calls With Proxy and In Java Security Java Secure Coding Java Password Hashing Java Input Validation Java Cryptography Basics Java KeyStore Basics Java TLS Basics Java SecureRandom Java JUnit Basics Java JUnit Test Methods JUnit Assertions JUnit Test Fixtures JUnit Parameterized Tests Mockito in Java Java Mock Objects Java Integration Testing Java Code Coverage Maven in Java Create a Maven Project in Java Maven Dependencies Maven Plugins Gradle in Java Gradle Build Gradle Dependencies Build Executable JAR in Java Build WAR File in Java HTTP Basics in Java Java Servlet Basics Servlet Lifecycle in Java HttpServletRequest in Java HttpServletResponse in Java JSP in Java JSTL in JSP REST API in Java JSON in Java Java Web Application Spring Framework Basics Spring Boot Tutorial Spring MVC Spring Data JPA Spring Security Spring Boot REST API Jakarta EE Basics Java Deployment JAR Deployment Java WAR Deployment Run Java as a Service Docker Java: Dockerize a Java Application Java Environment Variables and Configuration Java Logging Basics Java Production Setup Java JVM Options Java JVM Monitoring Java Hello World App Java Calculator App Java Number Guess Game Java Student Manager Java Library System Java Bank App Java Todo App Java File Manager Java Quiz App Java REST API Project Java Chat Server Java Employee Manager Java E-commerce API
Ask about this post
AI Ask about this post

Ask questions about Java Servlet Basics and get answers drawn from it.

Signed-in readers only.