HttpServletRequest in Java
HttpServletRequest in Java is the object a servlet container passes to your servlet to describe the incoming HTTP request. It gives you the parameters, URL parts, headers, cookies and body of the request, already parsed. Every doGet, doPost and other handler method receives one.
This lesson reads each part of a request in turn, with a small servlet and curl command for every feature. It ends with a registration endpoint that accepts both HTML forms and JSON. The examples run on Tomcat 11 in the student-portal app from Java Servlet Basics.
What HttpServletRequest Gives You
| Request part | Main methods |
|---|---|
| Parameters (query string and form fields) | getParameter, getParameterValues, getParameterMap |
| URL and method | getMethod, getRequestURI, getContextPath, getServletPath, getPathInfo, getQueryString |
| Headers | getHeader, getHeaders, getHeaderNames, getIntHeader, getDateHeader |
| Cookies | getCookies |
| Body | getReader, getInputStream, getContentType, getContentLengthLong |
| Client and server | getRemoteAddr, getScheme, getServerName, getServerPort |
| Data shared inside the server | setAttribute, getAttribute, getRequestDispatcher |
How it works:
- The container builds a new request object for every HTTP request and throws it away when the response is finished. Never store it in a field.
- Each item in this table is one part of the HTTP message described in HTTP Basics in Java.
Read Request Parameters
Parameters come from the query string (?course=java) and, for POST forms, from the body. HttpServletRequest merges both into one set.
| Method | Returns | When the parameter is missing |
|---|---|---|
getParameter(name) | First value as String | null |
getParameterValues(name) | All values as String[] | null |
getParameterNames() | Enumeration<String> of all names | Empty enumeration |
getParameterMap() | Read-only Map<String, String[]> | Empty map |
@WebServlet("/search")
public class SearchServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException {
String course = request.getParameter("course");
String level = request.getParameter("level");
String[] tags = request.getParameterValues("tag"); // repeated parameter
String page = request.getParameter("page");
int pageNumber = 1;
if (page != null) {
try {
pageNumber = Math.max(1, Integer.parseInt(page));
} catch (NumberFormatException e) {
response.sendError(HttpServletResponse.SC_BAD_REQUEST, "page must be a number");
return;
}
}
response.setContentType("text/plain;charset=UTF-8");
PrintWriter out = response.getWriter();
out.println("course = " + course);
out.println("level = " + (level != null ? level : "any"));
out.println("tags = " + (tags != null ? String.join(", ", tags) : "none"));
out.println("page = " + pageNumber);
out.println("all = " + request.getParameterMap().keySet());
}
}
curl "http://localhost:8080/student-portal/search?course=java&tag=oop&tag=threads&page=2"
Output:
course = java
level = any
tags = oop, threads
page = 2
all = [course, tag, page]
How it works:
getParameterreturnsnullfor a missing parameter, so always check before using the value.tagappears twice.getParameter("tag")would return onlyoop;getParameterValues("tag")returns both. Checkbox groups and multi-select lists send repeated names like this.- All values are strings. Convert numbers yourself and answer
400 Bad Requestwhen the conversion fails. - The container has already URL-decoded the values, so
Java%20%26%20Springarrives asJava & Spring.
Read HTML Form Data With POST
A form posted with method="post" sends application/x-www-form-urlencoded data in the body. You read it with the same getParameter calls.
@WebServlet("/feedback")
public class FeedbackServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws IOException {
request.setCharacterEncoding("UTF-8"); // before the first getParameter call
String name = request.getParameter("name");
String[] topics = request.getParameterValues("topic");
String comment = request.getParameter("comment");
response.setContentType("text/plain;charset=UTF-8");
PrintWriter out = response.getWriter();
out.println("From: " + name);
out.println("Topics: " + (topics == null ? 0 : topics.length));
out.println("Comment: " + comment);
}
}
curl --data-urlencode "name=Priyā" -d "topic=java&topic=servlets" \
--data-urlencode "comment=Great & clear!" \
http://localhost:8080/student-portal/feedback
Output:
From: Priyā
Topics: 2
Comment: Great & clear!
How it works:
--data-urlencodeencodesāand&correctly, just as a browser does when submitting a form.setCharacterEncoding("UTF-8")tells the container how to turn the body bytes into text. If it is called aftergetParameter, it has no effect andāmay appear as garbled characters.- Once the container has parsed form parameters, the body has been consumed;
getReader()will not return the raw text anymore.
Read the Request URL, Path and Method
A URL is split into parts that match how the container routed the request.
http://localhost:8080/student-portal/orders/42/items?sort=price
└─┬─┘ └───┬───┘ └┬─┘ └─────┬──────┘└──┬──┘└───┬───┘ └───┬────┘
scheme server port context path servlet path info query string
path
| Method | Value for the URL above |
|---|---|
getMethod() | GET |
getScheme() | http |
getServerName() | localhost |
getServerPort() | 8080 |
getContextPath() | /student-portal |
getServletPath() | /orders |
getPathInfo() | /42/items |
getQueryString() | sort=price |
getRequestURI() | /student-portal/orders/42/items |
getRequestURL() | http://localhost:8080/student-portal/orders/42/items (a StringBuffer) |
@WebServlet("/orders/*")
public class OrderServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException {
response.setContentType("text/plain;charset=UTF-8");
PrintWriter out = response.getWriter();
String pathInfo = request.getPathInfo(); // "/42/items"
String[] segments = pathInfo == null ? new String[0] : pathInfo.substring(1).split("/");
out.println("Method: " + request.getMethod());
out.println("Request URI: " + request.getRequestURI());
out.println("Order id: " + (segments.length > 0 ? segments[0] : "(none)"));
out.println("Sub-path: " + (segments.length > 1 ? segments[1] : "(none)"));
out.println("Sort by: " + request.getParameter("sort"));
}
}
curl "http://localhost:8080/student-portal/orders/42/items?sort=price"
Output:
Method: GET
Request URI: /student-portal/orders/42/items
Order id: 42
Sub-path: items
Sort by: price
How it works:
getContextPath() + getServletPath() + getPathInfo()always rebuilds the path part ofgetRequestURI().getPathInfo()isnullwhen nothing follows the servlet path, so check fornullbefore splitting.- Build links inside your app with
request.getContextPath(). Hard-coding/student-portalbreaks when the WAR is renamed.
Read Request Headers
Header lookups ignore case, so getHeader("user-agent") and getHeader("User-Agent") return the same value.
| Method | Use for |
|---|---|
getHeader(name) | One text value, or null |
getHeaders(name) | All values of a repeated header |
getHeaderNames() | Every header name |
getIntHeader(name) | A number; -1 if missing |
getDateHeader(name) | A date as epoch milliseconds; -1 if missing |
getContentType() | Shortcut for Content-Type |
getLocale() | Preferred language from Accept-Language |
@WebServlet("/headers")
public class HeaderServlet 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("User-Agent: " + request.getHeader("user-agent"));
out.println("Api-Version: " + request.getIntHeader("X-Api-Version"));
out.println("Locale: " + request.getLocale());
out.println("--- all headers ---");
Collections.list(request.getHeaderNames()).stream()
.sorted(String.CASE_INSENSITIVE_ORDER)
.forEach(name -> out.println(name + ": " + request.getHeader(name)));
}
}
curl -H "X-Api-Version: 2" -H "Accept-Language: ta-IN,en;q=0.8" \
http://localhost:8080/student-portal/headers
Output:
User-Agent: curl/8.5.0
Api-Version: 2
Locale: ta_IN
--- all headers ---
Accept: */*
Accept-Language: ta-IN,en;q=0.8
Host: localhost:8080
User-Agent: curl/8.5.0
X-Api-Version: 2
How it works:
getIntHeaderconverts the value for you. A header that is present but not a number throwsNumberFormatException.getLocale()picks the highest-priority language fromAccept-Language; here Tamil (India) beats English.Collections.listturns the old-styleEnumerationinto aList, so you can sort and stream it. Names are sorted without regard to case, because clients may send them in any case.
Read Cookies From the Request
getCookies() returns an array of Cookie objects, or null when the request has no cookies.
@WebServlet("/theme")
public class ThemeServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException {
String theme = "light"; // default
Cookie[] cookies = request.getCookies();
if (cookies != null) {
for (Cookie cookie : cookies) {
if (cookie.getName().equals("theme")) {
theme = cookie.getValue();
}
}
}
response.setContentType("text/plain;charset=UTF-8");
response.getWriter().println("Using theme: " + theme);
}
}
curl http://localhost:8080/student-portal/theme
curl -b "theme=dark; lang=ta" http://localhost:8080/student-portal/theme
Output:
Using theme: light
Using theme: dark
How it works:
curl -bsends aCookieheader, as a browser would after the server set the cookie earlier.- The
nullcheck is essential: the first visit from a new browser has no cookies at all. - Cookies only carry small text values. For login state, use the container's session (
request.getSession()), which stores data on the server and keeps only an ID in aJSESSIONIDcookie.
Read a JSON Request Body
APIs usually send JSON. Read it as text with getReader(), or as bytes with getInputStream() for files and other binary data.
@WebServlet("/api/scores")
public class ScoreServlet extends HttpServlet {
record ScoreInput(String student, int marks) {}
private static final Gson GSON = new Gson();
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws IOException {
String contentType = request.getContentType(); // may include ";charset=..."
if (contentType == null || !contentType.startsWith("application/json")) {
response.sendError(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE, "Send application/json");
return;
}
ScoreInput input = GSON.fromJson(request.getReader(), ScoreInput.class);
String grade = input.marks() >= 90 ? "A" : input.marks() >= 75 ? "B" : "C";
response.setContentType("text/plain;charset=UTF-8");
response.getWriter().println(input.student() + " scored " + input.marks() + " -> grade " + grade);
}
}
curl -H "Content-Type: application/json" -d '{"student":"Ravi","marks":78}' \
http://localhost:8080/student-portal/api/scores
curl -s -o /dev/null -w "%{http_code}\n" -d "student=Ravi" \
http://localhost:8080/student-portal/api/scores
Output:
Ravi scored 78 -> grade B
415
How it works:
- Checking
getContentType()first rejects bodies in the wrong format with415 Unsupported Media Type. getReader()decodes the body using the request's character encoding and streams it straight into Gson, without building a large string.- You can call either
getReader()orgetInputStream()on one request, not both; the second call throwsIllegalStateException.
Share Data With Request Attributes and Forward
Attributes are Java objects you attach to the request while it is inside the server. They are not sent by the client. A common use is to prepare data in one servlet and forward to another servlet or a JSP that displays it.
// ProfileServlet.java
@WebServlet("/profile")
public class ProfileServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String id = request.getParameter("id");
request.setAttribute("studentName", "7".equals(id) ? "Asha" : "Unknown student");
request.setAttribute("courses", List.of("Java", "Docker"));
// Server-side forward: the browser still sees /profile
request.getRequestDispatcher("/render-profile").forward(request, response);
}
}
// RenderProfileServlet.java
@WebServlet("/render-profile")
public class RenderProfileServlet extends HttpServlet {
@Override
@SuppressWarnings("unchecked")
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException {
String name = (String) request.getAttribute("studentName");
List<String> courses = (List<String>) request.getAttribute("courses");
response.setContentType("text/plain;charset=UTF-8");
response.getWriter().println(name + " is enrolled in " + courses);
response.getWriter().println("Original URI: " + request.getAttribute("jakarta.servlet.forward.request_uri"));
}
}
curl "http://localhost:8080/student-portal/profile?id=7"
Output:
Asha is enrolled in [Java, Docker]
Original URI: /student-portal/profile
| Parameter | Attribute | |
|---|---|---|
| Set by | The client (URL or body) | Your server code |
| Type | Always String | Any Java object |
| Lives for | One request | One request (or longer on session/context) |
| Read with | getParameter | getAttribute |
How it works:
getRequestDispatcher(path)takes a path inside the app, without the context path.forwardhands the same request and response objects to the target.- The forward happens inside Tomcat, so the client makes one request and sees one response.
- The container adds
jakarta.servlet.forward.*attributes so the target can still find the original URI.
Real-World Example: HttpServletRequest in Java for a Registration Endpoint
This endpoint registers a student for a course. It accepts both an HTML form and JSON, reads the course from the URL path, takes a referral code from a cookie, picks a greeting language from Accept-Language, validates everything and returns a JSON receipt.
package com.gocourse.portal;
import com.google.gson.Gson;
import com.google.gson.JsonParseException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
@WebServlet("/register/*")
public class RegistrationServlet extends HttpServlet {
record RegistrationForm(String name, String email, String batch) {}
record Receipt(String message, String course, String name, String email,
String batch, String referral, String clientIp) {}
record Errors(List<String> errors) {}
private static final Gson GSON = new Gson();
private static final Set<String> COURSES = Set.of("java", "python", "go");
private static final Set<String> BATCHES = Set.of("morning", "evening", "weekend");
private static final Map<String, String> GREETINGS = Map.of("ta", "Vanakkam", "hi", "Namaste");
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws IOException {
request.setCharacterEncoding("UTF-8");
// 1. Course from the URL: /register/java
String pathInfo = request.getPathInfo();
String course = pathInfo == null ? null : pathInfo.substring(1).toLowerCase();
if (course == null || !COURSES.contains(course)) {
sendJson(response, 404, new Errors(List.of("Unknown course: " + course)));
return;
}
// 2. Body as form fields or JSON, depending on Content-Type
RegistrationForm form;
String contentType = request.getContentType();
if (contentType != null && contentType.startsWith("application/json")) {
try {
form = GSON.fromJson(request.getReader(), RegistrationForm.class);
} catch (JsonParseException e) {
sendJson(response, 400, new Errors(List.of("Body is not valid JSON")));
return;
}
} else {
form = new RegistrationForm(request.getParameter("name"),
request.getParameter("email"), request.getParameter("batch"));
}
// 3. Validate every field and report all problems at once
List<String> errors = new ArrayList<>();
if (form == null || form.name() == null || form.name().isBlank()) errors.add("name is required");
if (form == null || form.email() == null || !form.email().matches("[^@\\s]+@[^@\\s]+\\.[a-z]{2,}")) {
errors.add("email is not valid");
}
if (form == null || form.batch() == null || !BATCHES.contains(form.batch())) {
errors.add("batch must be one of " + BATCHES);
}
if (!errors.isEmpty()) {
sendJson(response, 400, new Errors(errors));
return;
}
// 4. Optional extras from cookies, headers and the connection
String referral = "none";
Cookie[] cookies = request.getCookies();
if (cookies != null) {
for (Cookie cookie : cookies) {
if (cookie.getName().equals("ref")) referral = cookie.getValue();
}
}
String greeting = GREETINGS.getOrDefault(request.getLocale().getLanguage(), "Welcome");
String forwardedFor = request.getHeader("X-Forwarded-For"); // set by proxies
String clientIp = forwardedFor != null ? forwardedFor.split(",")[0].trim() : request.getRemoteAddr();
Receipt receipt = new Receipt(greeting + ", " + form.name() + "!", course,
form.name(), form.email(), form.batch(), referral, clientIp);
response.setHeader("Location", request.getContextPath() + "/register/" + course);
sendJson(response, 201, receipt);
}
private static void sendJson(HttpServletResponse response, int status, Object body)
throws IOException {
response.setStatus(status);
response.setContentType("application/json;charset=UTF-8");
response.getWriter().write(GSON.toJson(body));
}
}
Test it as a form, as JSON, and with bad input:
URL=http://localhost:8080/student-portal/register
curl -s -H "Accept-Language: ta-IN" -b "ref=GOC2026" \
-d "name=Asha&email=asha@example.com&batch=weekend" $URL/java; echo
curl -s -H "Content-Type: application/json" -H "X-Forwarded-For: 203.0.113.9" \
-d '{"name":"Ravi","email":"ravi@example.com","batch":"evening"}' $URL/python; echo
curl -s -w " (%{http_code})\n" -d "name=&email=wrong&batch=night" $URL/java
curl -s -w " (%{http_code})\n" -d "name=Meena" $URL/rust
Output:
{"message":"Vanakkam, Asha!","course":"java","name":"Asha","email":"asha@example.com","batch":"weekend","referral":"GOC2026","clientIp":"127.0.0.1"}
{"message":"Welcome, Ravi!","course":"python","name":"Ravi","email":"ravi@example.com","batch":"evening","referral":"none","clientIp":"203.0.113.9"}
{"errors":["name is required","email is not valid","batch must be one of [morning, evening, weekend]"]} (400)
{"errors":["Unknown course: rust"]} (404)
How it works:
- Path info for the resource.
getPathInfo()turns/register/javainto the course code, and an unknown course gets404. - Two body formats, one model.
getContentType()decides whether to read JSON withgetReader()or form fields withgetParameter(). Both paths produce the sameRegistrationFormrecord, so validation is written once. - Complete validation. All errors are collected and returned together with
400, so the user fixes everything in one try. The order of the batch names in the message can differ, becauseSet.ofdoes not keep a fixed order. - Extra context from the request. The referral code comes from a cookie (checked for
null), the greeting language fromgetLocale(), and the client address fromX-Forwarded-Forwhen a proxy or load balancer sits in front of Tomcat, otherwise fromgetRemoteAddr(). - Clean response. Success returns
201 Createdwith aLocationheader and a JSON receipt. Only trustX-Forwarded-Forwhen your own proxy sets it, because any client can send that header. To revisit how the container calls this method on a shared instance, see Servlet Lifecycle in Java.