Sobes.tech
Middle

What is the purpose of the ServletResponse interface?

sobes.tech AI

Answer from AI

The ServletResponse interface is used to send a response to the client (browser) from a servlet. It provides methods for:

  • Setting the content type (MIME type) of the response.
  • Setting the character encoding.
  • Writing the response body to the output stream.
  • Setting the HTTP status code of the response (e.g., 200 OK, 404 Not Found).
  • Adding HTTP headers to the response.
  • Redirecting the client to another URL.

Example of obtaining the output stream to write the response body:

// Import class
import javax.servlet.ServletResponse;
import java.io.PrintWriter;
import java.io.IOException;

// Inside a method like service
public void someMethod(ServletResponse response) throws IOException {
    response.setContentType("text/html"); // Set content type
    response.setCharacterEncoding("UTF-8"); // Set encoding

    PrintWriter out = response.getWriter(); // Get output stream
    out.println("<html><body>");
    out.println("<h1>Hello, world!</h1>");
    out.println("</body></html>");
    out.close(); // Close stream
}