Class RestResponse
- All Implemented Interfaces:
jakarta.servlet.http.HttpServletResponse,jakarta.servlet.ServletResponse
The RestResponse object is an extension of the
The primary methods on this class are:
RestResponse- Methods for setting response headers:
addHeader(HttpHeader)addHeader(String,String)containsHeader(String)getHeader(String)setCharacterEncoding(String)setContentType(String)setHeader(HttpHeader)setHeader(HttpPartSchema,String,Object)setHeader(String,Object)setHeader(String,String)setMaxHeaderLength(int)setSafeHeaders()setUnsafeHeaders()downloadAs(String)eTag(String)eTag(EntityTag)lastModified(Instant)lastModified(ZonedDateTime)cacheControl(String)cacheControl(CacheControl.Builder)
- Methods for setting response bodies:
flushBuffer()getDirectWriter(String)getNegotiatedOutputStream()getNegotiatedWriter()getSerializerMatch()getWriter()sendPlainText(String)sendRedirect(String)sendSafeRedirect(String,String...)setContentSchema(HttpPartSchema)setContent(Object)setSerializer(Serializer)setResponseBeanMeta(ResponseBeanMeta)setException(Throwable)
- Other:
- Methods for setting response headers:
-
Field Summary
Fields inherited from interface jakarta.servlet.http.HttpServletResponse
SC_ACCEPTED, SC_BAD_GATEWAY, SC_BAD_REQUEST, SC_CONFLICT, SC_CONTINUE, SC_CREATED, SC_EXPECTATION_FAILED, SC_FORBIDDEN, SC_FOUND, SC_GATEWAY_TIMEOUT, SC_GONE, SC_HTTP_VERSION_NOT_SUPPORTED, SC_INTERNAL_SERVER_ERROR, SC_LENGTH_REQUIRED, SC_METHOD_NOT_ALLOWED, SC_MISDIRECTED_REQUEST, SC_MOVED_PERMANENTLY, SC_MOVED_TEMPORARILY, SC_MULTIPLE_CHOICES, SC_NO_CONTENT, SC_NON_AUTHORITATIVE_INFORMATION, SC_NOT_ACCEPTABLE, SC_NOT_FOUND, SC_NOT_IMPLEMENTED, SC_NOT_MODIFIED, SC_OK, SC_PARTIAL_CONTENT, SC_PAYMENT_REQUIRED, SC_PERMANENT_REDIRECT, SC_PRECONDITION_FAILED, SC_PROXY_AUTHENTICATION_REQUIRED, SC_REQUEST_ENTITY_TOO_LARGE, SC_REQUEST_TIMEOUT, SC_REQUEST_URI_TOO_LONG, SC_REQUESTED_RANGE_NOT_SATISFIABLE, SC_RESET_CONTENT, SC_SEE_OTHER, SC_SERVICE_UNAVAILABLE, SC_SWITCHING_PROTOCOLS, SC_TEMPORARY_REDIRECT, SC_UNAUTHORIZED, SC_UNPROCESSABLE_CONTENT, SC_UNSUPPORTED_MEDIA_TYPE, SC_UPGRADE_REQUIRED, SC_USE_PROXY -
Method Summary
Modifier and TypeMethodDescriptionvoidAdds a response header with the given name and value.addHeader(HttpHeader header) Adds a response header.cacheControl(String value) Sets theCache-Control response header to the supplied directive string.cacheControl(CacheControl.Builder value) Sets theCache-Control response header from aCacheControl.Builder.downloadAs(String filename) SetsContent-Disposition toattachment so browsers typically download the body, using the given suggested file name (quotedfilenameparameter).Sets theETag response header to the supplied wire value.Sets theETag response header to the canonical wire form of the suppliedEntityTag.voidForces any content in the buffer to be written to the client.Shortcut for callinggetRequest().getAttributes() .byte[]Returns the captured (bounded) response body bytes for debug logging.longReturns the total number of response body bytes written, including any beyond the capture cap.Wrapper aroundServletResponseWrapper.getCharacterEncoding()that converts the value to aCharset.Returns the output that was set by callingsetContent(Object).<T> TgetContent(Class<T> c) Returns this value cast to the specified class.Returns the schema of the response content.Returns access to the innerRestContextof the class of this method.getDirectWriter(String contentType) Convenience method meant to be used when rendering directly to a browser with no buffering.jakarta.servlet.http.HttpServletResponseReturns the wrapped servlet response.Returns theContent-Type header stripped of the charset attribute if present.Equivalent toServletResponse.getOutputStream(), except wraps the output stream if anEncoderwas found that matched theAccept-Encoding header.Equivalent toServletResponse.getWriter(), except wraps the output stream if anEncoderwas found that matched theAccept-Encoding header and sets theContent-Encoding header to the appropriate value.Returns access to the innerRestOpContextof this method.jakarta.servlet.ServletOutputStreamReturns a ServletOutputStream suitable for writing binary data in the response.booleanReturnstrue ifgetOutputStream()has been called.Returns the metadata about this response.Returns the matching serializer and media type for this response.Returns the writer to the response content.booleanReturnstrue if the response contains output.booleanisContentOfType(Class<?> c) Returnstrue if this response object is of the specified type.lastModified(Instant value) Sets theLast-Modified response header to the supplied instant formatted as an RFC 7231 IMF-fixdate.lastModified(ZonedDateTime value) Sets theLast-Modified response header to the supplied date-time formatted as an RFC 7231 IMF-fixdate.sendPlainText(String text) Sets the output to a plain-text message regardless of the content type.voidsendRedirect(String uri) Redirects to the specified URI.voidsendSafeRedirect(String uri, String... allowedHosts) Redirects to the specified URI, but only if it's a relative path (interpreted persendRedirect(String)) or an absolute/protocol-relative URI whose host matches one ofallowedHosts .setAttribute(String name, Object value) Shortcut for callinggetRequest().setAttribute(String,Object) .setContent(Object output) Sets the HTTP output on the response.setContentSchema(HttpPartSchema schema) Specifies the schema for the response content.Sets the"Exception" attribute to the specified throwable.Sets a header on the request.voidSets a response header with the given name and value.setHeader(HttpHeader header) Sets a response header.setHeader(HttpPartSchema schema, String name, Object value) Sets a header on the request.setMaxHeaderLength(int value) Specifies the maximum length for header values.Shortcut for callingsetNoTrace( .true )Sets the"NoTrace" attribute to the specified boolean.Sets metadata about this response.Enables safe-header mode.setSerializer(Serializer value) Forces theSerializerused to serialize the response body set viasetContent(Object)(or an equivalent return from the REST method), instead of choosing one from theAccept header.Disables safe-header mode, restoring the pre-hardening behavior of passing header values through to the underlyingHttpServletResponseverbatim (aside from the usualsetMaxHeaderLength(int)truncation).sse()Creates a fluent Server-Sent Events helper for this response.Methods inherited from class jakarta.servlet.http.HttpServletResponseWrapper
addCookie, addDateHeader, addIntHeader, containsHeader, encodeRedirectURL, encodeURL, getHeader, getHeaderNames, getHeaders, getStatus, getTrailerFields, sendError, sendError, sendRedirect, sendRedirect, sendRedirect, setDateHeader, setIntHeader, setStatus, setTrailerFieldsMethods inherited from class jakarta.servlet.ServletResponseWrapper
getBufferSize, getCharacterEncoding, getContentType, getLocale, getResponse, isCommitted, isWrapperFor, isWrapperFor, reset, resetBuffer, setBufferSize, setCharacterEncoding, setCharacterEncoding, setContentLength, setContentLengthLong, setContentType, setLocale, setResponseMethods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, waitMethods inherited from interface jakarta.servlet.ServletResponse
getBufferSize, getCharacterEncoding, getContentType, getLocale, isCommitted, reset, resetBuffer, setBufferSize, setCharacterEncoding, setCharacterEncoding, setContentLength, setContentLengthLong, setContentType, setLocale
-
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 theRestRequest.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 benull (ignored).- Returns:
- This object.
-
addHeader
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:
addHeaderin interfacejakarta.servlet.http.HttpServletResponse- Overrides:
addHeaderin classjakarta.servlet.http.HttpServletResponseWrapper- Parameters:
name- The header name.value- The header value.
-
flushBuffer
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:
flushBufferin interfacejakarta.servlet.ServletResponse- Overrides:
flushBufferin classjakarta.servlet.ServletResponseWrapper- Throws:
IOException- If an I/O error occurred.
-
getAttributes
Shortcut for callinggetRequest().getAttributes() .- Returns:
- The request attributes object.
-
getCharset
Wrapper aroundServletResponseWrapper.getCharacterEncoding()that converts the value to aCharset.- Returns:
- The request character encoding converted to a
Charset, ornull if no character encoding is set.
-
getContent
Returns the output that was set by callingsetContent(Object).If it's null, then
setContent(Object)wasn't called.
If it contains an empty, thensetObject( was called.null )
Otherwise,setContent(Object)was called with a non-null value.- Returns:
- The output object, or
null ifsetContent(Object)was never called.
-
getContent
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 benull .- 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 innerRestContextof the class of this method.- Returns:
- The
RestContextof this class. Nevernull .
-
getDirectWriter
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 theContent-Type on the response.- Returns:
- The raw writer.
- Throws:
IOException- Thrown by underlying stream.
-
getHttpServletResponse
Returns the wrapped servlet response.- Returns:
- The wrapped servlet response.
-
getMediaType
Returns theContent-Type header stripped of the charset attribute if present.- Returns:
- The
media-type portion of theContent-Type header.
-
getNegotiatedOutputStream
Equivalent toServletResponse.getOutputStream(), except wraps the output stream if anEncoderwas found that matched theAccept-Encoding header.- Returns:
- A negotiated output stream.
- Throws:
NotAcceptable- If unsupported Accept-Encoding value specified.IOException- Thrown by underlying stream.
-
getNegotiatedWriter
Equivalent toServletResponse.getWriter(), except wraps the output stream if anEncoderwas found that matched theAccept-Encoding header and sets theContent-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 innerRestOpContextof this method.- Returns:
- The
RestOpContextof this method. Nevernull .
-
getOutputStream
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 orgetWriter may be called to write the content, not both, except when reset has been called.- Specified by:
getOutputStreamin interfacejakarta.servlet.ServletResponse- Overrides:
getOutputStreamin classjakarta.servlet.ServletResponseWrapper- Returns:
- The stream.
- Throws:
IOException- If stream could not be accessed.
-
getOutputStreamCalled
Returnstrue ifgetOutputStream()has been called.- Returns:
true ifgetOutputStream()has been called.
-
getResponseBeanMeta
Returns the metadata about this response.- Returns:
- The metadata about this response.
Can benull if the response method has no@Responsemetadata (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:
getWriterin interfacejakarta.servlet.ServletResponse- Overrides:
getWriterin classjakarta.servlet.ServletResponseWrapper- Returns:
- The writer.
- Throws:
IOException- If writer could not be accessed.
-
hasContent
Returnstrue if the response contains output.This implies
setContent(Object)has been called on this object.Note that this also returns
true even ifsetContent(Object)was called with anull value as this means the response contains an output value ofnull as opposed to no value at all.- Returns:
true if the response contains output.
-
isContentOfType
Returnstrue if this response object is of the specified type.- Parameters:
c- The type to check against.
Must not benull .- 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 benull .- 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
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; usesendSafeRedirect(String,String...)instead in that case, which validates the target is either relative or points at an allow-listed host.- Specified by:
sendRedirectin interfacejakarta.servlet.http.HttpServletResponse- Overrides:
sendRedirectin classjakarta.servlet.http.HttpServletResponseWrapper- Parameters:
uri- The redirection URL.- Throws:
IOException- If an input or output exception occurs
-
sendSafeRedirect
Redirects to the specified URI, but only if it's a relative path (interpreted persendRedirect(String)) or an absolute/protocol-relative URI whose host matches one ofallowedHosts .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-relativeuri is allowed to target. Ignored for relative URIs.- Throws:
IOException- If an input or output exception occurs.BadRequest- Ifuri is absolute or protocol-relative and its host isn't inallowedHosts .
-
setAttribute
Shortcut for callinggetRequest().setAttribute(String,Object) .- Parameters:
name- The property name.value- The property value.- Returns:
- This object.
-
setContent
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(RestResponseres ,@Path UUIDpersonId ) { Personperson = getPersonById(personId );res .setContent(person ); }Notes:
-
Calling this method with a
null value is NOT the same as not calling this method at all.
Anull output value means we want to serializenull as a response (e.g. as a JSONnull ).
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.
-
Calling this method with a
-
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 benull (clears any previously-set schema).- Returns:
- This object.
-
setSerializer
Forces theSerializerused to serialize the response body set viasetContent(Object)(or an equivalent return from the REST method), instead of choosing one from theAccept header.SerializedPojoProcessorusesgetSerializerMatch(), which returns aSerializerMatchbuilt from this serializer when non-null .Content-Type is still applied by the response processor: it prefersgetMediaType()if set, then the match media type, thenSerializer.getResponseContentType(). CallServletResponseWrapper.setContentType(String)(or another header setter) if you need a specific type before serialization runs.- Parameters:
value- The serializer to use. Can benull to clear the override and use normalAccept negotiation on the nextgetSerializerMatch()call.- Returns:
- This object.
-
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 returnsnull . The captured copy is capped at the formatter's body cap (default 8 KB); usegetCachedContentLength()for the full byte count.- Returns:
- The captured response body bytes, or
null if body caching was not installed.
-
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
-1if body caching was not installed.
-
setException
Sets the"Exception" attribute to the specified throwable.This exception is surfaced by the debug pipeline as the
thrownof 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 benull (ignored).- Returns:
- This object.
-
downloadAs
SetsContent-Disposition toattachment so browsers typically download the body, using the given suggested file name (quotedfilenameparameter).Shorthand for
setHeader(ContentDisposition.attachment(filename)).Example
res .downloadAs("example.pdf" ).setContent(pdfBytes );- Parameters:
filename- Suggested download name. Must not benull , blank, or contain CR/LF.- Returns:
- This object.
- Throws:
IllegalArgumentException- Iffilenameis invalid.- See Also:
-
eTag
Sets theETag 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 withW/ (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 benull ; must match theentity-taggrammar per RFC 7232 §2.3.- Returns:
- This object.
- Throws:
IllegalArgumentException- Ifvalueis malformed.- See Also:
-
eTag
Sets theETag response header to the canonical wire form of the suppliedEntityTag.- Parameters:
value- The entity tag. Must not benull .- Returns:
- This object.
- Throws:
IllegalArgumentException- Ifvalueisnull .
-
lastModified
Sets theLast-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 benull .- Returns:
- This object.
- Throws:
IllegalArgumentException- Ifvalueisnull .- See Also:
-
lastModified
Sets theLast-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 benull .- Returns:
- This object.
- Throws:
IllegalArgumentException- Ifvalueisnull .
-
cacheControl
Sets theCache-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 benull .- Returns:
- This object.
- Throws:
IllegalArgumentException- Ifvalueisnull .- See Also:
-
cacheControl
Sets theCache-Control response header from aCacheControl.Builder.Example:
res .cacheControl(CacheControl.create ().publicCache().maxAge(3600));// Cache-Control: public, max-age=3600 - Parameters:
value- The builder. Must not benull .- Returns:
- This object.
- Throws:
IllegalArgumentException- Ifvalueisnull .
-
setHeader
public RestResponse setHeader(HttpPartSchema schema, String name, Object value) throws SchemaValidationException, SerializeException Sets a header on the request.- Parameters:
schema- The schema to use to serialize the header, ornull 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
public RestResponse setHeader(String name, Object value) throws SchemaValidationException, SerializeException 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 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:
setHeaderin interfacejakarta.servlet.http.HttpServletResponse- Overrides:
setHeaderin classjakarta.servlet.http.HttpServletResponseWrapper- Parameters:
name- The header name.value- The header value.
-
setMaxHeaderLength
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 is8096 .- Returns:
- This object.
-
setNoTrace
Shortcut for callingsetNoTrace( .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 benull (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; seesetUnsafeHeaders()to opt back out.- Returns:
- This object.
-
setUnsafeHeaders
Disables safe-header mode, restoring the pre-hardening behavior of passing header values through to the underlyingHttpServletResponseverbatim (aside from the usualsetMaxHeaderLength(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.
-