HttpServletResponse Interface with Example (Jakarta EE)

The HttpServletResponse interface is an important interface of the Java Servlet API that allows a servlet to send a response to the client. This interface provides methods for manipulating response headers, writing content to the response body, and setting status codes.

Introduction to HttpServletResponse

The HttpServletResponse interface extends the ServletResponse interface to provide HTTP-specific functionality in sending a response. It is part of the jakarta.servlet.http package.

Key Features of HttpServletResponse

  • Response Headers: Add or modify HTTP response headers.
  • Content Type: Set the MIME type of the response.
  • Status Codes: Set the HTTP status code for the response.
  • Cookies: Add cookies to the response.
  • Output Stream: Write binary data to the response.
  • PrintWriter: Write character data to the response.

Commonly Used Methods

  • addCookie(Cookie cookie): Adds a specified cookie to the response.
  • addHeader(String name, String value): Adds a header with a given name and value to the response.
  • setContentType(String type): Sets the content type of the response.
  • setStatus(int sc): Sets the status code for the response.
  • getOutputStream(): Returns a ServletOutputStream suitable for writing binary data.
  • getWriter(): Returns a PrintWriter object that can send character text to the client.
  • sendRedirect(String location): Sends a temporary redirect response to the client using the specified redirect location URL.
  • setContentLength(int len): Sets the length of the content being returned to the client.

Example Code

Let's create a simple servlet that demonstrates the use of HttpServletResponse methods to send a response back to the client.

Example: Sending a Response

package com.example;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.io.PrintWriter;

@WebServlet("/responseexample")
public class ResponseExampleServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html");

        // Setting a response header
        response.addHeader("Custom-Header", "This is a custom header");

        // Setting a status code
        response.setStatus(HttpServletResponse.SC_OK);

        // Adding a cookie
        Cookie userCookie = new Cookie("user", "john_doe");
        userCookie.setMaxAge(60 * 60); // 1 hour
        response.addCookie(userCookie);

        // Writing response content
        PrintWriter out = response.getWriter();
        out.println("<html><body>");
        out.println("<h1>HttpServletResponse Example</h1>");
        out.println("<p>This response demonstrates the use of HttpServletResponse methods.</p>");
        out.println("</body></html>");
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // Example of sending a redirect
        String redirectUrl = request.getContextPath() + "/anotherpage";
        response.sendRedirect(redirectUrl);
    }
}

Explanation

  • Annotation: The @WebServlet annotation defines the URL pattern (/responseexample) for accessing this servlet.
  • setContentType Method: Sets the content type of the response to "text/html".
  • addHeader Method: Adds a custom header to the response.
  • setStatus Method: Sets the HTTP status code to 200 (OK).
  • addCookie Method: Adds a cookie to the response.
  • getWriter Method: Retrieves a PrintWriter object to write character data to the response.
  • sendRedirect Method: Redirects the client to another URL.

Conclusion

The HttpServletResponse interface is essential for sending responses to clients in Java web applications. By understanding and using its methods, developers can manipulate response headers, set content types, add cookies, and write data to the response body. This enables the creation of dynamic, interactive web applications that can effectively communicate with clients.

For more detailed information on HttpServletResponse, refer to the Jakarta Servlet API documentation.

Related Servlet Posts

Comments