Class RestResponse

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

public final 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:

See Also:
  • Method Details

    • getContext

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

      Returns access to the inner RestOpContext of this method.
      Returns:
      The RestOpContext of this method. Never null.
    • 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.setOutput(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.
    • getAttributes

      Shortcut for calling getRequest().getAttributes().
      Returns:
      The request attributes object.
    • 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.
    • 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.
    • 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.
    • sendPlainText

      Sets the output to a plain-text message regardless of the content type.
      Parameters:
      text - The output text to send.
      Returns:
      This object.
      Throws:
      IOException - If a problem occurred trying to write to the writer.
    • 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.
    • 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.
    • 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.
    • 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.
    • 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.
    • getMediaType

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

      public Charset getCharset()
      Wrapper around ServletResponseWrapper.getCharacterEncoding() that converts the value to a Charset.
      Returns:
      The request character encoding converted to a Charset.
    • 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.

      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
    • 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.
    • 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

      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.
    • 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
      Returns:
      This object.
    • setException

      Sets the "Exception" attribute to the specified throwable.

      This exception is used by CallLogger for logging purposes.

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

      Sets the "NoTrace" attribute to the specified boolean.

      This flag is used by CallLogger and tells it not to log the current request.

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

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

      Sets the "Debug" attribute to the specified boolean.

      This flag is used by CallLogger to help determine how a request should be logged.

      Parameters:
      b - The attribute value.
      Returns:
      This object.
      Throws:
      IOException - If bodies could not be cached.
    • setDebug

      Shortcut for calling setDebug(true).
      Returns:
      This object.
      Throws:
      IOException - If bodies could not be cached.
    • getResponseBeanMeta

      Returns the metadata about this response.
      Returns:
      The metadata about this response.
      Never null.
    • setResponseBeanMeta

      Sets metadata about this response.
      Parameters:
      rbm - The metadata about this response.
      Returns:
      This object.
    • isContentOfType

      public boolean isContentOfType(Class<?> c)
      Returns true if this response object is of the specified type.
      Parameters:
      c - The type to check against.
      Returns:
      true if this response object is of the specified type.
    • 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.
      Returns:
      This value cast to the specified class, or null if the object doesn't exist or isn't the specified type.
    • getHttpServletResponse

      public jakarta.servlet.http.HttpServletResponse getHttpServletResponse()
      Returns the wrapped servlet request.
      Returns:
      The wrapped servlet request.
    • 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.
    • setSafeHeaders

      Enabled safe-header mode.

      When enabled, invalid characters such as CTRL characters will be stripped from header values before they get set.

      Returns:
      This object.
    • 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.
    • 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.
    • setHeader

      public RestResponse setHeader(Header header)
      Sets a response header.

      Any previous header values are removed.

      Value is added at the end of the headers.

      Parameters:
      header - The header.
      Returns:
      This object.
    • addHeader

      public RestResponse addHeader(Header header)
      Adds a response header.

      Any previous header values are preserved.

      Value is added at the end of the headers.

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

      If the header is a SerializedHeader and the serializer session is not set, it will be set to the one returned by RestRequest.getPartSerializerSession() before serialization.

      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.
      Returns:
      This object.
    • getSerializerMatch

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

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