HttpServletResponse in Java
HttpServletResponse in Java is the object a servlet uses to build the HTTP response sent back to the client. Through it you set the status code, headers, cookies and body, send errors and redirects, and stream files. The container creates one for every request and passes it to doGet, doPost and the other handler methods.
This lesson covers each part of a response with a small servlet and a curl command that shows exactly what the client receives. It ends with a course catalog endpoint that returns JSON or CSV and supports browser caching. The examples run on Tomcat 11 (Servlet 6.1) in the student-portal app from Java Servlet Basics.
What HttpServletResponse Controls
| Response part | Main methods |
|---|---|
| Status code | setStatus, sendError, sendRedirect, getStatus |
| Content type and encoding | setContentType, setCharacterEncoding, setContentLengthLong |
| Body | getWriter (text), getOutputStream (bytes) |
| Headers | setHeader, addHeader, setIntHeader, setDateHeader, containsHeader |
| Cookies | addCookie |
| Buffer | isCommitted, setBufferSize, flushBuffer, reset, resetBuffer |
HTTP/1.1 200 <- status line (setStatus)
Content-Type: application/json;charset=UTF-8 <- headers (setContentType, setHeader)
Set-Cookie: theme=dark; Path=/ <- cookie (addCookie)
<- blank line
{"course":"java"} <- body (getWriter / getOutputStream)
How it works:
- The response mirrors the request you read in HttpServletRequest in Java: a status line, headers, a blank line and a body.
- Tomcat keeps the status and headers in memory until the response is committed (first bytes sent). After that, they can no longer change.
- Tomcat 11 sends no reason phrase, so the status line reads
HTTP/1.1 200rather thanHTTP/1.1 200 OK.
Set the Status Code and Content Type
A response is 200 OK by default. Call setStatus to send a different code, and setContentType so the client knows how to read the body.
@WebServlet("/api/ping")
public class PingServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException {
response.setStatus(HttpServletResponse.SC_OK); // 200 (the default)
response.setContentType("application/json;charset=UTF-8"); // type + encoding together
response.getWriter().write("{\"status\":\"up\"}");
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws IOException {
response.setStatus(HttpServletResponse.SC_ACCEPTED); // 202
response.setContentType("text/plain;charset=UTF-8");
response.getWriter().write("Ping queued");
}
}
curl -i http://localhost:8080/student-portal/api/ping
curl -i -X POST http://localhost:8080/student-portal/api/ping
Output:
HTTP/1.1 200
Content-Type: application/json;charset=UTF-8
Content-Length: 15
Date: Wed, 18 Nov 2026 05:30:00 GMT
{"status":"up"}
HTTP/1.1 202
Content-Type: text/plain;charset=UTF-8
Content-Length: 11
Date: Wed, 18 Nov 2026 05:30:01 GMT
Ping queued
| Constant | Code | Typical use |
|---|---|---|
SC_OK | 200 | Successful read or update |
SC_CREATED | 201 | A new resource was created |
SC_ACCEPTED | 202 | Work was queued for later |
SC_NO_CONTENT | 204 | Success with no body (delete) |
SC_BAD_REQUEST | 400 | Invalid input |
SC_UNAUTHORIZED | 401 | Login required |
SC_FORBIDDEN | 403 | Logged in but not allowed |
SC_NOT_FOUND | 404 | Resource does not exist |
SC_CONFLICT | 409 | Duplicate or conflicting data |
SC_INTERNAL_SERVER_ERROR | 500 | Unexpected server failure |
How it works:
curl -iprints the status line and headers before the body.- Put
;charset=UTF-8insetContentType, or callsetCharacterEncoding("UTF-8"), beforegetWriter(). The writer picks its encoding when it is created. - Tomcat calculated
Content-Lengthbecause the whole body fit in its output buffer.
Write Text, HTML and JSON Response Bodies
Use getWriter() for text and getOutputStream() for bytes. You may call only one of them per response; calling the other throws IllegalStateException.
| Method | Returns | Use for |
|---|---|---|
getWriter() | PrintWriter | HTML, JSON, CSV, plain text |
getOutputStream() | ServletOutputStream | Images, PDFs, ZIP files, any binary data |
@WebServlet("/welcome")
public class WelcomeServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException {
String name = request.getParameter("name");
String safeName = escapeHtml(name == null ? "guest" : name);
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
out.println("<!DOCTYPE html>");
out.println("<html><body>");
out.println("<h1>Welcome, " + safeName + "!</h1>");
out.println("</body></html>");
}
// Replace characters that have meaning in HTML
private static String escapeHtml(String text) {
return text.replace("&", "&").replace("<", "<")
.replace(">", ">").replace("\"", """);
}
}
curl "http://localhost:8080/student-portal/welcome?name=Asha"
curl "http://localhost:8080/student-portal/welcome?name=%3Cscript%3Ealert(1)%3C/script%3E"
Output:
<!DOCTYPE html>
<html><body>
<h1>Welcome, Asha!</h1>
</body></html>
<!DOCTYPE html>
<html><body>
<h1>Welcome, <script>alert(1)</script>!</h1>
</body></html>
How it works:
- The second request tries to inject a
<script>tag.escapeHtmlturns it into harmless text, so the browser shows it instead of running it. - Escape every user-supplied value you put into HTML. Writing HTML with
printlngets tedious quickly, which is why the next lessons move the HTML into JSP pages. - You do not need to close the writer. The container flushes and closes it when the request finishes.
Set Response Headers in a Servlet
Headers carry extra information such as caching rules, the location of a new resource or custom metadata.
| Method | Behaviour |
|---|---|
setHeader(name, value) | Sets a header, replacing any existing value |
addHeader(name, value) | Adds another value, keeping existing ones |
setIntHeader(name, int) | Sets a numeric header |
setDateHeader(name, millis) | Sets an HTTP date from epoch milliseconds |
containsHeader(name) | Checks whether a header was already set |
@WebServlet("/api/notice")
public class NoticeServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException {
long oneHourLater = System.currentTimeMillis() + 3_600_000;
response.setHeader("Cache-Control", "public, max-age=3600"); // cache for 1 hour
response.setDateHeader("Expires", oneHourLater);
response.setIntHeader("X-Notice-Count", 1);
response.addHeader("X-Course-Tag", "java");
response.addHeader("X-Course-Tag", "servlets"); // second value
response.setContentType("text/plain;charset=UTF-8");
response.getWriter().println("Classes resume on Monday.");
response.getWriter().println("Cache-Control set? " + response.containsHeader("cache-control"));
}
}
curl -i http://localhost:8080/student-portal/api/notice
Output:
HTTP/1.1 200
Cache-Control: public, max-age=3600
Expires: Wed, 18 Nov 2026 06:30:00 GMT
X-Notice-Count: 1
X-Course-Tag: java
X-Course-Tag: servlets
Content-Type: text/plain;charset=UTF-8
Content-Length: 50
Date: Wed, 18 Nov 2026 05:30:00 GMT
Classes resume on Monday.
Cache-Control set? true
How it works:
addHeadersends twoX-Course-Taglines.setHeaderwould have replaced the first value with the second.setDateHeaderformats the time in the standard HTTP date format and in GMT, so you never build that string yourself.- Header names are case-insensitive, so
containsHeader("cache-control")findsCache-Control.
Send Errors With sendError
sendError sets an error status, clears the buffer and lets the container produce the error page. It is the quickest way to stop processing a bad request.
@WebServlet("/courses/*")
public class CourseServlet extends HttpServlet {
private static final Map<String, String> COURSES = Map.of(
"java", "Java Programming", "python", "Python Programming");
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException {
String pathInfo = request.getPathInfo(); // "/java"
if (pathInfo == null || pathInfo.equals("/")) {
response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Course code missing");
return; // always stop after sendError
}
String title = COURSES.get(pathInfo.substring(1));
if (title == null) {
response.sendError(HttpServletResponse.SC_NOT_FOUND, "No such course");
return;
}
response.setContentType("text/plain;charset=UTF-8");
response.getWriter().println(title);
}
}
curl -s -w " (%{http_code})\n" http://localhost:8080/student-portal/courses/java
curl -s -o /dev/null -w "%{http_code}\n" http://localhost:8080/student-portal/courses/rust
curl -s -o /dev/null -w "%{http_code}\n" http://localhost:8080/student-portal/courses/
Output:
Java Programming
(200)
404
400
How it works:
- After
sendErrorthe response is committed. Writing more output or callingsetStatushas no effect, soreturnright away. - Tomcat shows its own HTML error page by default. To show a branded page, map the code in
web.xml:
<error-page>
<error-code>404</error-code>
<location>/WEB-INF/errors/not-found.html</location>
</error-page>
Note: For JSON APIs, prefer
setStatus(404)plus a JSON error body instead ofsendError. Clients can then read the error message in the same format as successful responses.
Redirect the Browser With sendRedirect
A redirect tells the client to make a new request to another URL. The classic use is Post/Redirect/Get: after a form is saved, redirect to a result page so a browser refresh does not resubmit the form.
| Method | Status sent |
|---|---|
sendRedirect(location) | 302 Found |
sendRedirect(location, sc) (Servlet 6.1) | The code you pass, such as 303 or 301 |
sendRedirect(location, sc, clearBuffer) (Servlet 6.1) | Your code, with control over the buffer |
@WebServlet("/enroll")
public class EnrollServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws IOException {
String course = request.getParameter("course");
// ... save the enrollment here ...
String target = request.getContextPath() + "/enroll/done?course="
+ URLEncoder.encode(course, StandardCharsets.UTF_8);
response.sendRedirect(target, HttpServletResponse.SC_SEE_OTHER); // 303
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException {
// Old URL moved permanently to the new course list
response.sendRedirect(request.getContextPath() + "/courses",
HttpServletResponse.SC_MOVED_PERMANENTLY); // 301
}
}
curl -i -d "course=Java & Spring" http://localhost:8080/student-portal/enroll
curl -s -o /dev/null -w "%{http_code} -> %{redirect_url}\n" http://localhost:8080/student-portal/enroll
Output:
HTTP/1.1 303
Location: /student-portal/enroll/done?course=Java+%26+Spring
Content-Length: 0
Date: Wed, 18 Nov 2026 05:30:00 GMT
301 -> http://localhost:8080/student-portal/courses
How it works:
303 See Othertells the browser to follow up with aGET, which is exactly what Post/Redirect/Get needs.- Always start the location with
request.getContextPath()so the redirect still works if the app is deployed under another name. URLEncoder.encodemakes&and spaces safe inside the query string.- A redirect differs from a forward: a forward stays inside the server and the browser never sees the second URL.
Set Cookies on the Response
addCookie adds a Set-Cookie header. The browser stores the cookie and sends it back on later requests.
@WebServlet("/settings/theme")
public class ThemeSettingServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws IOException {
String theme = "dark".equals(request.getParameter("theme")) ? "dark" : "light";
Cookie themeCookie = new Cookie("theme", theme);
themeCookie.setPath(request.getContextPath()); // send it for the whole app
themeCookie.setMaxAge(60 * 60 * 24 * 30); // 30 days, in seconds
themeCookie.setHttpOnly(true); // hidden from JavaScript
themeCookie.setSecure(request.isSecure()); // HTTPS only when served over HTTPS
themeCookie.setAttribute("SameSite", "Lax"); // limit cross-site sending
response.addCookie(themeCookie);
response.setContentType("text/plain;charset=UTF-8");
response.getWriter().println("Theme saved: " + theme);
}
@Override
protected void doDelete(HttpServletRequest request, HttpServletResponse response) {
Cookie expired = new Cookie("theme", "");
expired.setPath(request.getContextPath());
expired.setMaxAge(0); // 0 = delete now
response.addCookie(expired);
response.setStatus(HttpServletResponse.SC_NO_CONTENT);
}
}
curl -i -d "theme=dark" http://localhost:8080/student-portal/settings/theme
curl -i -X DELETE http://localhost:8080/student-portal/settings/theme
Output:
HTTP/1.1 200
Set-Cookie: theme=dark; Max-Age=2592000; Expires=Fri, 18 Dec 2026 05:30:00 GMT; Path=/student-portal; HttpOnly; SameSite=Lax
Content-Type: text/plain;charset=UTF-8
Content-Length: 18
Date: Wed, 18 Nov 2026 05:30:00 GMT
Theme saved: dark
HTTP/1.1 204
Set-Cookie: theme=; Max-Age=0; Expires=Thu, 01 Jan 1970 00:00:10 GMT; Path=/student-portal
Date: Wed, 18 Nov 2026 05:30:01 GMT
How it works:
setMaxAgeis in seconds. A negative value (the default) makes a session cookie that disappears when the browser closes.setAttribute("SameSite", "Lax")uses the generic cookie attribute support added in Servlet 6.0.- To delete a cookie, send one with the same name and path and
Max-Age=0. Secureis absent here becausecurlused plain HTTP andrequest.isSecure()returnedfalse.
Send a File Download With getOutputStream
Binary content goes through getOutputStream(). The Content-Disposition header tells the browser to save the file instead of displaying it.
@WebServlet("/certificates/download")
public class CertificateDownloadServlet extends HttpServlet {
private static final Path CERT_DIR = Path.of("/srv/student-portal/certificates");
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException {
String studentId = request.getParameter("student");
if (studentId == null || !studentId.matches("\\d{1,6}")) { // digits only: blocks ../ tricks
response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Invalid student id");
return;
}
Path pdf = CERT_DIR.resolve("certificate-" + studentId + ".pdf");
if (!Files.isRegularFile(pdf)) {
response.sendError(HttpServletResponse.SC_NOT_FOUND);
return;
}
response.setContentType("application/pdf");
response.setContentLengthLong(Files.size(pdf));
response.setHeader("Content-Disposition",
"attachment; filename=\"certificate-" + studentId + ".pdf\"");
Files.copy(pdf, response.getOutputStream()); // stream the bytes
}
}
curl -s -D - -o cert.pdf "http://localhost:8080/student-portal/certificates/download?student=1042"
curl -s -o /dev/null -w "%{http_code}\n" "http://localhost:8080/student-portal/certificates/download?student=../etc"
Output:
HTTP/1.1 200
Content-Disposition: attachment; filename="certificate-1042.pdf"
Content-Type: application/pdf
Content-Length: 48213
Date: Wed, 18 Nov 2026 05:30:00 GMT
400
How it works:
curl -D -prints the headers while-o cert.pdfsaves the body to a file.Files.copy(path, outputStream)streams the file in chunks, so even large files use little memory. File reading is covered in Java Files API.- Validating the id with a regular expression stops path traversal such as
../etc. Never build a file path from raw user input.
Response Buffering and Committed Responses
Tomcat collects output in a buffer (8 KB by default). The response is committed when the buffer fills, when you call flushBuffer(), or when the request ends. After commit, status and headers are fixed.
@WebServlet("/buffer-demo")
public class BufferDemoServlet 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("Buffer size: " + response.getBufferSize());
out.println("Committed before flush? " + response.isCommitted());
response.resetBuffer(); // throw away the text so far
out.println("Fresh start after resetBuffer()");
response.flushBuffer(); // send headers + body now
out.println("Committed after flush? " + response.isCommitted());
try {
response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
} catch (IllegalStateException e) {
out.println("sendError failed: response already committed");
}
}
}
curl -s -w "(%{http_code})\n" http://localhost:8080/student-portal/buffer-demo
Output:
Fresh start after resetBuffer()
Committed after flush? true
sendError failed: response already committed
(200)
How it works:
resetBuffer()drops the first two lines because they were still in the buffer.reset()would also clear the status and headers.- Once
flushBuffer()sends the response,sendErrorthrowsIllegalStateExceptionand the client keeps the200status. - Decide the status and headers first, then write the body. Large streaming responses commit early, so validate input before you start writing.
Real-World Example: HttpServletResponse in Java for a Course Catalog Endpoint
This endpoint returns the course catalog as JSON or CSV. It supports conditional requests with an ETag, so browsers and API clients re-download the catalog only when it changes. Errors come back as JSON.
package com.gocourse.portal;
import com.google.gson.Gson;
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.util.List;
import java.util.Map;
@WebServlet("/api/catalog")
public class CatalogServlet extends HttpServlet {
record Course(String code, String title, int lessons, double feeInr) {}
private static final Gson GSON = new Gson();
private static final List<Course> CATALOG = List.of(
new Course("java", "Java Programming", 306, 4999.0),
new Course("python", "Python Programming", 180, 3999.0),
new Course("go", "Go Language", 120, 2999.0));
// A version tag that changes whenever the catalog content changes
private static final String ETAG = "\"catalog-" + Integer.toHexString(CATALOG.hashCode()) + "\"";
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException {
String format = request.getParameter("format");
if (format == null) format = "json";
if (!format.equals("json") && !format.equals("csv")) {
sendJsonError(response, HttpServletResponse.SC_BAD_REQUEST,
"format must be json or csv");
return;
}
// 1. Caching headers go on every successful response
response.setHeader("ETag", ETAG);
response.setHeader("Cache-Control", "no-cache"); // store it, but check before reuse
// 2. Client already has this version: answer 304 with no body
if (ETAG.equals(request.getHeader("If-None-Match"))) {
response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
return;
}
// 3. Full response in the requested format
if (format.equals("csv")) {
response.setContentType("text/csv;charset=UTF-8");
response.setHeader("Content-Disposition", "attachment; filename=\"catalog.csv\"");
PrintWriter out = response.getWriter();
out.println("code,title,lessons,fee_inr");
for (Course course : CATALOG) {
out.printf("%s,%s,%d,%.2f%n", course.code(), course.title(),
course.lessons(), course.feeInr());
}
} else {
response.setContentType("application/json;charset=UTF-8");
response.getWriter().write(GSON.toJson(Map.of("count", CATALOG.size(), "courses", CATALOG)));
}
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws IOException {
response.setHeader("Allow", "GET, HEAD, OPTIONS");
sendJsonError(response, HttpServletResponse.SC_METHOD_NOT_ALLOWED, "The catalog is read-only");
}
private static void sendJsonError(HttpServletResponse response, int status, String message)
throws IOException {
response.setStatus(status);
response.setContentType("application/json;charset=UTF-8");
response.getWriter().write(GSON.toJson(Map.of("status", status, "error", message)));
}
}
Request the catalog, repeat the request with the ETag, download CSV and try invalid input:
URL=http://localhost:8080/student-portal/api/catalog
curl -s -D - $URL; echo
ETAG=$(curl -s -D - -o /dev/null $URL | grep -i '^etag' | cut -d' ' -f2 | tr -d '\r')
curl -s -o /dev/null -w "%{http_code}\n" -H "If-None-Match: $ETAG" $URL
curl -s "$URL?format=csv"
curl -s -w " (%{http_code})\n" "$URL?format=xml"
curl -s -w " (%{http_code})\n" -X POST $URL
Output:
HTTP/1.1 200
ETag: "catalog-5f3a91c2"
Cache-Control: no-cache
Content-Type: application/json;charset=UTF-8
Content-Length: 239
Date: Wed, 18 Nov 2026 05:30:00 GMT
{"count":3,"courses":[{"code":"java","title":"Java Programming","lessons":306,"feeInr":4999.0},{"code":"python","title":"Python Programming","lessons":180,"feeInr":3999.0},{"code":"go","title":"Go Language","lessons":120,"feeInr":2999.0}]}
304
code,title,lessons,fee_inr
java,Java Programming,306,4999.00
python,Python Programming,180,3999.00
go,Go Language,120,2999.00
{"status":400,"error":"format must be json or csv"} (400)
{"status":405,"error":"The catalog is read-only"} (405)
How it works:
- Validate first, write later. The
formatcheck runs before anything is written, so the error response can still set its own status and content type. - ETag caching. The
ETagheader identifies the catalog version. When the client sends it back inIf-None-Matchand nothing has changed, the servlet returns304 Not Modifiedwith no body, saving bandwidth. The exact tag value depends on the catalog contents. - Two formats, one data source. The same
CATALOGlist becomes JSON through Gson or CSV throughprintf. The CSV response also setsContent-Dispositionso browsers save it ascatalog.csv. The keys in the JSON object may appear in a different order, becauseMap.ofhas no fixed order. - Consistent errors.
sendJsonErrorsets the status, the JSON content type and a small JSON body, so API clients handle every error the same way. The405response also lists the allowed methods in theAllowheader, as the HTTP standard expects. A full API built on these response techniques comes in REST API in Java.