Class RestResponse

java.lang.Object
jakarta.servlet.ServletResponseWrapper
jakarta.servlet.http.HttpServletResponseWrapper
org.apache.juneau.rest.server.RestResponse
All Implemented Interfaces:
jakarta.servlet.http.HttpServletResponse, jakarta.servlet.ServletResponse

public class RestResponse extends jakarta.servlet.http.HttpServletResponseWrapper
Represents an HTTP response for a REST resource.

The RestResponse object is an extension of the HttpServletResponse class with various built-in convenience methods for use in building REST interfaces. It can be accessed by passing it as a parameter on your REST Java method:

@RestPost(...) public Object myMethod(RestResponse res) {...}

The primary methods on this class are:

  • Method Details

    • addHeader

      Adds a response header.

      Any previous header values are preserved.

      Value is added at the end of the headers.

      If the header is a HttpUriHeader, the URI will be resolved using the RestRequest.getUriResolver() object.

      Note that per RFC2616, only headers defined as comma-delimited lists [i.e., #(values)] should be defined as multiple message header fields.

      Parameters:
      header - The header.
      Can be null (ignored).
      Returns:
      This object.
    • addHeader

      public void addHeader(String name, String value)
      Adds a response header with the given name and value.

      This method allows response headers to have multiple values.

      A no-op of either the name or value is null.

      Note that per RFC2616, only headers defined as comma-delimited lists [i.e., #(values)] should be defined as multiple message header fields.

      Specified by:
      addHeader in interface jakarta.servlet.http.HttpServletResponse
      Overrides:
      addHeader in class jakarta.servlet.http.HttpServletResponseWrapper
      Parameters:
      name - The header name.
      value - The header value.
    • flushBuffer

      public void flushBuffer() throws IOException
      Forces any content in the buffer to be written to the client.

      A call to this method automatically commits the response, meaning the status code and headers will be written.

      Specified by:
      flushBuffer in interface jakarta.servlet.ServletResponse
      Overrides:
      flushBuffer in class jakarta.servlet.ServletResponseWrapper
      Throws:
      IOException - If an I/O error occurred.
    • getAttributes

      Shortcut for calling getRequest().getAttributes().
      Returns:
      The request attributes object.
    • getCharset

      public Charset getCharset()
      Wrapper around ServletResponseWrapper.getCharacterEncoding() that converts the value to a Charset.
      Returns:
      The request character encoding converted to a Charset, or null if no character encoding is set.
    • getContent

      Returns the output that was set by calling setContent(Object).

      If it's null, then setContent(Object) wasn't called.
      If it contains an empty, then setObject(null) was called.
      Otherwise, setContent(Object) was called with a non-null value.

      Returns:
      The output object, or null if setContent(Object) was never called.
    • getContent

      public <T> T getContent(Class<T> c)
      Returns this value cast to the specified class.
      Type Parameters:
      T - The class to cast to.
      Parameters:
      c - The class to cast to.
      Must not be null.
      Returns:
      This value cast to the specified class, or null if the object doesn't exist or isn't the specified type.
    • getContentSchema

      Returns the schema of the response content.
      Returns:
      The schema of the response content, never null.
    • getContext

      Returns access to the inner RestContext of the class of this method.
      Returns:
      The RestContext of this class. Never null.
    • getDirectWriter

      public PrintWriter getDirectWriter(String contentType) throws IOException
      Convenience method meant to be used when rendering directly to a browser with no buffering.

      Sets the header "x-content-type-options=nosniff" so that output is rendered immediately on IE and Chrome without any buffering for content-type sniffing.

      This can be useful if you want to render a streaming 'console' on a web page.

      Parameters:
      contentType - The value to set as the Content-Type on the response.
      Returns:
      The raw writer.
      Throws:
      IOException - Thrown by underlying stream.
    • getHttpServletResponse

      public jakarta.servlet.http.HttpServletResponse getHttpServletResponse()
      Returns the wrapped servlet response.
      Returns:
      The wrapped servlet response.
    • getMediaType

      Returns the Content-Type header stripped of the charset attribute if present.
      Returns:
      The media-type portion of the Content-Type header.
    • getNegotiatedOutputStream

      Equivalent to ServletResponse.getOutputStream(), except wraps the output stream if an Encoder was found that matched the Accept-Encoding header.
      Returns:
      A negotiated output stream.
      Throws:
      NotAcceptable - If unsupported Accept-Encoding value specified.
      IOException - Thrown by underlying stream.
    • getNegotiatedWriter

      Equivalent to ServletResponse.getWriter(), except wraps the output stream if an Encoder was found that matched the Accept-Encoding header and sets the Content-Encoding header to the appropriate value.
      Returns:
      The negotiated writer.
      Throws:
      NotAcceptable - If unsupported charset in request header Accept-Charset.
      IOException - Thrown by underlying stream.
    • getOpContext

      Returns access to the inner RestOpContext of this method.
      Returns:
      The RestOpContext of this method. Never null.
    • getOutputStream

      public jakarta.servlet.ServletOutputStream getOutputStream() throws IOException
      Returns a ServletOutputStream suitable for writing binary data in the response.

      The servlet container does not encode the binary data.

      Calling flush() on the ServletOutputStream commits the response. Either this method or getWriter may be called to write the content, not both, except when reset has been called.

      Specified by:
      getOutputStream in interface jakarta.servlet.ServletResponse
      Overrides:
      getOutputStream in class jakarta.servlet.ServletResponseWrapper
      Returns:
      The stream.
      Throws:
      IOException - If stream could not be accessed.
    • getOutputStreamCalled

      public boolean getOutputStreamCalled()
      Returns true if getOutputStream() has been called.
      Returns:
      true if getOutputStream() has been called.
    • getResponseBeanMeta

      Returns the metadata about this response.
      Returns:
      The metadata about this response.
      Can be null if the response method has no @Response metadata (or was explicitly cleared).
    • getSerializerMatch

      Returns the matching serializer and media type for this response.
      Returns:
      The matching serializer, never null.
    • getWriter

      Returns the writer to the response content.

      This methods bypasses any specified encoders and returns a regular unbuffered writer. Use the getNegotiatedWriter() method if you want to use the matched encoder (if any).

      Specified by:
      getWriter in interface jakarta.servlet.ServletResponse
      Overrides:
      getWriter in class jakarta.servlet.ServletResponseWrapper
      Returns:
      The writer.
      Throws:
      IOException - If writer could not be accessed.
    • hasContent

      public boolean hasContent()
      Returns true if the response contains output.

      This implies setContent(Object) has been called on this object.

      Note that this also returns true even if setContent(Object) was called with a null value as this means the response contains an output value of null as opposed to no value at all.

      Returns:
      true if the response contains output.
    • isContentOfType

      public boolean isContentOfType(Class<?> c)
      Returns true if this response object is of the specified type.
      Parameters:
      c - The type to check against.
      Must not be null.
      Returns:
      true if this response object is of the specified type.
    • sendPlainText

      Sets the output to a plain-text message regardless of the content type.
      Parameters:
      text - The output text to send.
      Must not be null.
      Returns:
      This object.
      Throws:
      IOException - If a problem occurred trying to write to the writer.
    • sse

      Creates a fluent Server-Sent Events helper for this response.
      Returns:
      The SSE response helper.
      Throws:
      IOException - If the writer could not be created.
    • sendRedirect

      public void sendRedirect(String uri) throws IOException
      Redirects to the specified URI.

      Relative URIs are always interpreted as relative to the context root. This is similar to how WAS handles redirect requests, and is different from how Tomcat handles redirect requests.

      This method forwards uri to the container as-is. If the target is built from request input (e.g. a query parameter or header value), a caller can steer users to an arbitrary external site; use sendSafeRedirect(String,String...) instead in that case, which validates the target is either relative or points at an allow-listed host.

      Specified by:
      sendRedirect in interface jakarta.servlet.http.HttpServletResponse
      Overrides:
      sendRedirect in class jakarta.servlet.http.HttpServletResponseWrapper
      Parameters:
      uri - The redirection URL.
      Throws:
      IOException - If an input or output exception occurs
    • sendSafeRedirect

      public void sendSafeRedirect(String uri, String... allowedHosts) throws IOException
      Redirects to the specified URI, but only if it's a relative path (interpreted per sendRedirect(String)) or an absolute/protocol-relative URI whose host matches one of allowedHosts.

      Intended for use when the redirect target is derived from request input rather than a fixed, trusted literal, so that input can't be used to redirect a user to an arbitrary external site.

      Parameters:
      uri - The redirection URL.
      allowedHosts - The hosts (case-insensitive) an absolute or protocol-relative uri is allowed to target. Ignored for relative URIs.
      Throws:
      IOException - If an input or output exception occurs.
      BadRequest - If uri is absolute or protocol-relative and its host isn't in allowedHosts.
    • setAttribute

      public RestResponse setAttribute(String name, Object value)
      Shortcut for calling getRequest().setAttribute(String,Object).
      Parameters:
      name - The property name.
      value - The property value.
      Returns:
      This object.
    • setContent

      public RestResponse setContent(Object output)
      Sets the HTTP output on the response.

      The object type can be anything allowed by the registered response handlers.

      Calling this method is functionally equivalent to returning the object in the REST Java method.

      Example:

      @RestGet("/example2/{personId}") public void doGet(RestResponse res, @Path UUID personId) { Person person = getPersonById(personId); res.setContent(person); }

      Notes:
      • Calling this method with a null value is NOT the same as not calling this method at all.
        A null output value means we want to serialize null as a response (e.g. as a JSON null).
        Not calling this method or returning a value means you're handing the response yourself via the underlying stream or writer.
      See Also:
      Parameters:
      output - The output to serialize to the connection.
      Returns:
      This object.
    • setContentSchema

      Specifies the schema for the response content.

      Used by schema-aware serializers such as OpenApiSerializer. Ignored by other serializers.

      Parameters:
      schema - The content schema
      Can be null (clears any previously-set schema).
      Returns:
      This object.
    • setSerializer

      Forces the Serializer used to serialize the response body set via setContent(Object) (or an equivalent return from the REST method), instead of choosing one from the Accept header.

      SerializedPojoProcessor uses getSerializerMatch(), which returns a SerializerMatch built from this serializer when non-null.

      Content-Type is still applied by the response processor: it prefers getMediaType() if set, then the match media type, then Serializer.getResponseContentType(). Call ServletResponseWrapper.setContentType(String) (or another header setter) if you need a specific type before serialization runs.

      Parameters:
      value - The serializer to use. Can be null to clear the override and use normal Accept negotiation on the next getSerializerMatch() call.
      Returns:
      This object.
    • getCachedContent

      public byte[] getCachedContent()
      Returns the captured (bounded) response body bytes for debug logging.

      Populated by the two-phase debug pipeline only when the resolved logger is loggable at FINEST; otherwise returns null. The captured copy is capped at the formatter's body cap (default 8 KB); use getCachedContentLength() for the full byte count.

      Returns:
      The captured response body bytes, or null if body caching was not installed.
    • getCachedContentLength

      public long getCachedContentLength()
      Returns the total number of response body bytes written, including any beyond the capture cap.
      Returns:
      The total response body length in bytes, or -1 if body caching was not installed.
    • setException

      Sets the "Exception" attribute to the specified throwable.

      This exception is surfaced by the debug pipeline as the thrown of the emitted log record.

      Parameters:
      t - The attribute value.
      Returns:
      This object.
    • setHeader

      Sets a response header.

      Any previous header values are removed.

      Value is added at the end of the headers.

      Parameters:
      header - The header.
      Can be null (ignored).
      Returns:
      This object.
    • downloadAs

      public RestResponse downloadAs(String filename)
      Sets Content-Disposition to attachment so browsers typically download the body, using the given suggested file name (quoted filename parameter).

      Shorthand for setHeader(ContentDisposition.attachment(filename)).

      Example

      res.downloadAs("example.pdf").setContent(pdfBytes);

      Parameters:
      filename - Suggested download name. Must not be null, blank, or contain CR/LF.
      Returns:
      This object.
      Throws:
      IllegalArgumentException - If filename is invalid.
      See Also:
    • eTag

      public RestResponse eTag(String value)
      Sets the ETag response header to the supplied wire value.

      The value is validated through EntityTag.of(Object) — strong tags must be quoted ("v1"), weak tags must be prefixed with W/ (W/"v1"), and the wildcard * is accepted. The header is serialized in canonical form (re-quoted for strong tags, W/-prefixed for weak tags).

      Example:

      res.eTag("\"v42\""); // ETag: "v42" res.eTag("W/\"v42\""); // ETag: W/"v42"

      Parameters:
      value - The entity-tag wire value. Must not be null; must match the entity-tag grammar per RFC 7232 §2.3.
      Returns:
      This object.
      Throws:
      IllegalArgumentException - If value is malformed.
      See Also:
    • eTag

      public RestResponse eTag(EntityTag value)
      Sets the ETag response header to the canonical wire form of the supplied EntityTag.
      Parameters:
      value - The entity tag. Must not be null.
      Returns:
      This object.
      Throws:
      IllegalArgumentException - If value is null.
    • lastModified

      Sets the Last-Modified response header to the supplied instant formatted as an RFC 7231 IMF-fixdate.

      The instant is rendered in GMT regardless of the JVM's default timezone. The fractional-second portion is truncated, matching the per-spec one-second resolution of HTTP-date timestamps.

      Example:

      res.lastModified(Instant.parse("2026-05-22T00:00:00Z")); // Last-Modified: Fri, 22 May 2026 00:00:00 GMT

      Parameters:
      value - The last-modified timestamp. Must not be null.
      Returns:
      This object.
      Throws:
      IllegalArgumentException - If value is null.
      See Also:
    • lastModified

      Sets the Last-Modified response header to the supplied date-time formatted as an RFC 7231 IMF-fixdate.

      The supplied date-time is converted to GMT and truncated to whole seconds before formatting.

      Parameters:
      value - The last-modified timestamp. Must not be null.
      Returns:
      This object.
      Throws:
      IllegalArgumentException - If value is null.
    • cacheControl

      Sets the Cache-Control response header to the supplied directive string.

      The value is written verbatim — the caller is responsible for supplying a comma-separated directive list per RFC 9111 §5.2.

      Parameters:
      value - The directive list (e.g. "public, max-age=3600"). Must not be null.
      Returns:
      This object.
      Throws:
      IllegalArgumentException - If value is null.
      See Also:
    • cacheControl

      Sets the Cache-Control response header from a CacheControl.Builder.
      Example:

      res.cacheControl(CacheControl.create().publicCache().maxAge(3600)); // Cache-Control: public, max-age=3600

      Parameters:
      value - The builder. Must not be null.
      Returns:
      This object.
      Throws:
      IllegalArgumentException - If value is null.
    • setHeader

      Sets a header on the request.
      Parameters:
      schema - The schema to use to serialize the header, or null to use the default schema.
      name - The header name.
      value - The header value.
      • Can be any POJO.
      • Converted to a string using the specified part serializer.
      Returns:
      This object.
      Throws:
      SchemaValidationException - Header failed schema validation.
      SerializeException - Header could not be serialized.
    • setHeader

      Sets a header on the request.
      Parameters:
      name - The header name.
      value - The header value.
      • Can be any POJO.
      • Converted to a string using the specified part serializer.
      Returns:
      This object.
      Throws:
      SchemaValidationException - Header failed schema validation.
      SerializeException - Header could not be serialized.
    • setHeader

      public void setHeader(String name, String value)
      Sets a response header with the given name and value.

      If the header had already been set, the new value overwrites the previous one.

      The HttpServletResponseWrapper.containsHeader(String) method can be used to test for the presence of a header before setting its value.

      Specified by:
      setHeader in interface jakarta.servlet.http.HttpServletResponse
      Overrides:
      setHeader in class jakarta.servlet.http.HttpServletResponseWrapper
      Parameters:
      name - The header name.
      value - The header value.
    • setMaxHeaderLength

      public RestResponse setMaxHeaderLength(int value)
      Specifies the maximum length for header values.

      Header values that exceed this length will get truncated.

      Parameters:
      value - The new value for this setting. The default is 8096.
      Returns:
      This object.
    • setNoTrace

      Shortcut for calling setNoTrace(true).
      Returns:
      This object.
    • setNoTrace

      Sets the "NoTrace" attribute to the specified boolean.

      This flag tells the framework not to trace the current request: the access-log record for the call is still emitted, but without the exception's stack trace. A No-Trace: true request header has the same effect; when both are present, the attribute wins.

      Parameters:
      b - The attribute value.
      Returns:
      This object.
    • setResponseBeanMeta

      Sets metadata about this response.
      Parameters:
      rbm - The metadata about this response.
      Can be null (clears the metadata).
      Returns:
      This object.
    • setSafeHeaders

      Enables safe-header mode.

      When enabled (the default), invalid characters such as CTRL characters (including a raw CR or LF that could otherwise be used to inject an additional header or split the response) are stripped from header values via StringUtils.stripInvalidHttpHeaderChars(String) before they get set. This is a no-op call retained for apps that called it explicitly before this became the default; see setUnsafeHeaders() to opt back out.

      Returns:
      This object.
    • setUnsafeHeaders

      Disables safe-header mode, restoring the pre-hardening behavior of passing header values through to the underlying HttpServletResponse verbatim (aside from the usual setMaxHeaderLength(int) truncation).

      Only call this for a header value the application has already validated itself; most servlet containers reject a raw CR/LF in a header value outright regardless of this setting, but other control characters may still pass through once safe-header mode is off.

      Returns:
      This object.