Java.Servlet.What is the ServletResponse interface for?

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

TaskMethod/Usage
Set content typesetContentType("text/html")
Set character encodingsetCharacterEncoding("UTF-8")
Get output stream for binarygetOutputStream()
Get writer for textgetWriter()
Set response buffer sizesetBufferSize(int size)
Control response bufferingflushBuffer(), 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

FeaturePurpose
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 methodsgetWriter(), setContentType(), getOutputStream()
This entry was posted in Без рубрики. Bookmark the permalink.