HttpServletResponse in Java

Su Suriya Ravichandran Updated 18 Nov 2026
13 min read ·Lesson 271 of 306

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 partMain methods
Status codesetStatus, sendError, sendRedirect, getStatus
Content type and encodingsetContentType, setCharacterEncoding, setContentLengthLong
BodygetWriter (text), getOutputStream (bytes)
HeaderssetHeader, addHeader, setIntHeader, setDateHeader, containsHeader
CookiesaddCookie
BufferisCommitted, 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 200 rather than HTTP/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
ConstantCodeTypical use
SC_OK200Successful read or update
SC_CREATED201A new resource was created
SC_ACCEPTED202Work was queued for later
SC_NO_CONTENT204Success with no body (delete)
SC_BAD_REQUEST400Invalid input
SC_UNAUTHORIZED401Login required
SC_FORBIDDEN403Logged in but not allowed
SC_NOT_FOUND404Resource does not exist
SC_CONFLICT409Duplicate or conflicting data
SC_INTERNAL_SERVER_ERROR500Unexpected server failure

How it works:

  • curl -i prints the status line and headers before the body.
  • Put ;charset=UTF-8 in setContentType, or call setCharacterEncoding("UTF-8"), before getWriter(). The writer picks its encoding when it is created.
  • Tomcat calculated Content-Length because 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.

MethodReturnsUse for
getWriter()PrintWriterHTML, JSON, CSV, plain text
getOutputStream()ServletOutputStreamImages, 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. escapeHtml turns 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 println gets 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.

MethodBehaviour
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:

  • addHeader sends two X-Course-Tag lines. setHeader would have replaced the first value with the second.
  • setDateHeader formats 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") finds Cache-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 sendError the response is committed. Writing more output or calling setStatus has no effect, so return right 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 of sendError. 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.

MethodStatus 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 Other tells the browser to follow up with a GET, 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.encode makes & 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:

  • setMaxAge is 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.
  • Secure is absent here because curl used plain HTTP and request.isSecure() returned false.

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.pdf saves 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, sendError throws IllegalStateException and the client keeps the 200 status.
  • 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:

  1. Validate first, write later. The format check runs before anything is written, so the error response can still set its own status and content type.
  2. ETag caching. The ETag header identifies the catalog version. When the client sends it back in If-None-Match and nothing has changed, the servlet returns 304 Not Modified with no body, saving bandwidth. The exact tag value depends on the catalog contents.
  3. Two formats, one data source. The same CATALOG list becomes JSON through Gson or CSV through printf. The CSV response also sets Content-Disposition so browsers save it as catalog.csv. The keys in the JSON object may appear in a different order, because Map.of has no fixed order.
  4. Consistent errors. sendJsonError sets the status, the JSON content type and a small JSON body, so API clients handle every error the same way. The 405 response also lists the allowed methods in the Allow header, as the HTTP standard expects. A full API built on these response techniques comes in REST API 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 HttpServletResponse in Java and get answers drawn from it.

Signed-in readers only.