MTI TEK
  • Home
  • About
  • LLMs
  • Docker
  • Kubernetes
  • Java
  • All Resources
Java Servlet | ServletResponse
  1. Configuring Response Content
    1. Setting the content type
    2. Configuring character encoding
    3. Writing response content
  2. Managing response headers
  3. Client redirection
  4. Working with cookies

  1. Configuring Response Content
    The ServletResponse interface provides essential methods for configuring how content is delivered to the client. Proper configuration of content type, encoding, and output methods ensures that browsers can correctly interpret and display your response data.
    1. Setting the content type
      The content type informs the client's browser how to interpret the response data. This must be set before writing any content to the response.
      • setContentType(String)
        Sets the MIME type of the response. This method should be called before obtaining a PrintWriter or OutputStream.

        Examples:
        The MIME type "text/html", for HTML content.
        The MIME type "text/plain", for plain text.
        The MIME type "application/json", for JSON data.
        The MIME type "image/jpeg", for JPEG images.
    2. Configuring character encoding
      Character encoding determines how text characters are converted to bytes for transmission. UTF-8 is the recommended encoding for web applications as it supports all Unicode characters. You can specify the encoding of the response content using the setContentType method, or use the setCharacterEncoding method, which is specifically designed for this purpose:
      • setContentType(String)
        Sets both content type and encoding in a single call. The encoding specification follows the MIME type after a semicolon.

        Example:
        The MIME type "text/html;charset=UTF-8" sets both the content type to "text/html" and the encoding to "UTF-8".

      • setCharacterEncoding(String)
        Sets only the character encoding. This method can be called independently of setContentType.

        Example:
        setCharacterEncoding("UTF-8").
    3. Writing response content
      ServletResponse provides two methods for writing content to the client. You must choose one or the other, but cannot use both in the same response.
      • PrintWriter ServletResponse.getWriter();
        This method is used to write character-based content such as HTML, XML, JSON, or plain text. The PrintWriter automatically handles character encoding conversion.

      • ServletOutputStream ServletResponse.getOutputStream();
        This method is used to write binary content such as images, PDFs, or any byte-based data. Use this when you need direct control over the byte output.
  2. Managing response headers
    HTTP headers provide metadata about the response and control browser behavior. Headers must be set before the response is committed (before writing content).
    • void setHeader(String, String)
      Sets a response header with the given name and value. If the header already exists, it replaces the previous value.

    • void addHeader(String, String)
      Adds a response header with the given name and value. This method allows multiple headers with the same name.

    • void setIntHeader(String, int)
      Sets a response header with the given name and integer value. Useful for headers like Content-Length.

    • void addIntHeader(String, int)
      Adds a response header with the given name and integer value.

    • void setDateHeader(String, long)
      Sets a response header with the given name and date value. The date is specified as milliseconds since epoch.

    • void addDateHeader(String, long)
      Adds a response header with the given name and date value.
  3. Client redirection
    Redirection instructs the client's browser to make a new request to a different URL. This is commonly used after form submissions or for URL restructuring. To redirect the request to another page, use the method: sendRedirect(String).
    The argument passed to this method can be interpreted as:
    • A path relative to the current request URL:
      If the path passed as a parameter to this method does not start with the "/" character.
      response.sendRedirect("formParameters.htm");
    • A path relative to the web application root:
      If the path passed as a parameter to this method starts with the "/" character.
      response.sendRedirect("/mywebapp/formParameters.htm");
    You can also specify a redirect path to another domain.
    response.sendRedirect("http://www.mtitek.com/mywebapp/formParameters.htm");
    The sendRedirect method performs the following actions:
    • Clears any existing response content buffer;
    • Sets the response status code to 302 (Found/Moved Temporarily);
    • Adds a "Location" header to the response with the redirection URL provided as the method argument.
    You can achieve the same behavior by manually setting the appropriate response headers:
    response.setStatus(HttpServletResponse.SC_MOVED_TEMPORARILY);
    response.setHeader("Location", "http://www.mtitek.com/tutorials/linux/index.php");
    However, be aware that any content generated before this code is executed will not be cleared and will still be sent to the client.
  4. Working with cookies
    Cookies are small pieces of data stored on the client side and sent back to the server with subsequent requests. They are commonly used for session management, user preferences, and tracking.
    • addCookie(Cookie)
      Adds a cookie to the response. The cookie will be sent to the client and stored according to its attributes.

    A cookie has:
    - a name (required);
    - a value (required);
    - and other optional attributes such as expiration date, domain, path, secure flag, and HttpOnly flag.

    The constructor Cookie(String, String) creates a Cookie object with the name and value specified as arguments. Additional attributes can be set using setter methods on the Cookie object before adding it to the response.
© 2025 mtitek