The ServletResponse interface is used to build and send the response from a servlet back to the client (usually a browser or an HTTP client).
📦 What Is ServletResponse?
It’s a core part of the Servlet API:
javax.servlet.ServletResponse
It represents the output stream that the servlet uses to send:
- HTML
- JSON
- Binary data (e.g. images, files)
- Status codes
- Headers
➡️ The servlet container creates a ServletResponse object for each request and passes it to your servlet’s service() / doGet() / doPost() method.
🧪 Basic Example: Writing HTML to Response
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
res.setContentType("text/html");
PrintWriter out = res.getWriter();
out.println("<h1>Hello, Stanley!</h1>");
}
🧠 Key Responsibilities of ServletResponse
| Task | Method/Usage |
|---|---|
| Set content type | setContentType("text/html") |
| Set character encoding | setCharacterEncoding("UTF-8") |
| Get output stream for binary | getOutputStream() |
| Get writer for text | getWriter() |
| Set response buffer size | setBufferSize(int size) |
| Control response buffering | flushBuffer(), resetBuffer() |
⚡ Difference Between getWriter() and getOutputStream()
| Use getWriter() for… | Text (HTML, JSON, plain text) | | Use getOutputStream() for… | Binary data (images, PDFs, zip files) |
❗ You can use only one of these per response — not both.
✅ Typical Workflow in a Servlet
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
// Set status and headers
res.setStatus(HttpServletResponse.SC_OK);
res.setContentType("application/json");
res.setCharacterEncoding("UTF-8");
// Write JSON response
PrintWriter out = res.getWriter();
out.print("{\"message\": \"Data received\"}");
out.flush();
}
✅ Summary
| Feature | Purpose |
|---|---|
| What is it? | Interface to build the response to send to the client |
| Who provides it? | Servlet container |
| Common use? | Write HTML, JSON, or binary data |
| Key methods | getWriter(), setContentType(), getOutputStream() |