Java Servlet Basics
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 ───────────┘
| Object | Type | Use it to |
|---|---|---|
| Request | HttpServletRequest | Read parameters, headers, cookies and the body |
| Response | HttpServletResponse | Set the status, headers and content type, and write the body |
| Container | Tomcat, Jetty, GlassFish | Run 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.servletpackage. Code that importsjavax.servletbelongs 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 version | Servlet API | Package | Minimum Java |
|---|---|---|---|
| 9.0 | 4.0 | javax.servlet | 8 |
| 10.1 | 6.0 | jakarta.servlet | 11 |
| 11.0 | 6.1 | jakarta.servlet | 17 |
How it works:
jakarta.servlet-api6.1.0 matches Tomcat 11. Compiling against a newer API than the server supports can causeNoSuchMethodErrorat run time.- Build with
mvn packageand copytarget/student-portal.warto Tomcat'swebappsfolder.
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.setContentTypemust come beforegetWriter(). 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
200by 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.
| Method | Called for | Default behaviour if not overridden |
|---|---|---|
doGet | GET | 405 Method Not Allowed |
doPost | POST | 405 Method Not Allowed |
doPut | PUT | 405 Method Not Allowed |
doDelete | DELETE | 405 Method Not Allowed |
doPatch | PATCH (Servlet 6.1) | 405 Method Not Allowed |
doHead | HEAD | Runs doGet and drops the body |
doOptions | OPTIONS | Lists 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
POSTreaches the inheriteddoPost, which sends405. doOptionsinspects which methods your class overrides and builds theAllowheader automatically.HEADcomes free withGET. Some containers also listTRACEwhen 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.
| Pattern | Example | Matches |
|---|---|---|
| Exact | /hello | Only /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:
urlPatternstakes an array, so one servlet can serve several URLs.getServletPath()returns the part that matched the pattern, andgetPathInfo()returns the rest. REST-style servlets read IDs frompathInfo.namegives the servlet a name that appears in logs and can be referenced fromweb.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 firstgetParametercall; otherwise the container decodes the body with its default charset.sendError(400, ...)sets the status and makes Tomcat return its error page.escapeHtmlturns<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.
Gsonobjects are thread-safe, so onestatic finalinstance can be shared by all requests.- Gson has
compilescope, so the build copies it intoWEB-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
@WebServlet | web.xml | |
|---|---|---|
| Where | On the class | One XML file |
| Change mapping without recompiling | No | Yes |
| Good for | Most new apps | Third-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-listservesindex.htmlwhen a user opens the app's root URL.- If both declare the same servlet name,
web.xmlwins, 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:
- One servlet, one resource. The pattern
/api/courses/*sends both/api/coursesand/api/courses/7to this class.getPathInfo()tells them apart. - Method per action.
doGetreads,doPostcreates anddoDeleteremoves.PUTandPATCHare not overridden, so the container answers them with405. - JSON in and out.
request.getReader()streams the body straight into Gson, andwriteJsonsets the status and content type before writing. - Clear errors. Bad IDs and bad bodies return
400, unknown IDs return404, and successful creates return201with aLocationheader. - Thread safety. The container creates one instance of the servlet and calls it from many threads at once, so the data uses
ConcurrentSkipListMapandAtomicInteger. 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.