Top Description Inners Fields Constructors Methods
org.springframework.web.servlet.mvc.method.annotation

public Class ResponseBodyEmitter

extends Object
Class Inheritance
Known Direct Subclasses
org.springframework.web.servlet.mvc.method.annotation.SseEmitter
Imports
java.io.IOException, java.util.LinkedHashSet, .Set, java.util.function.Consumer, org.springframework.http.MediaType, org.springframework.http.server.ServerHttpResponse, org.springframework.lang.Nullable, org.springframework.util.Assert, .ObjectUtils

A controller method return value type for asynchronous request processing where one or more objects are written to the response.

While org.springframework.web.context.request.async.DeferredResult is used to produce a single result, a ResponseBodyEmitter can be used to send multiple objects where each object is written with a compatible org.springframework.http.converter.HttpMessageConverter.

Supported as a return type on its own as well as within a org.springframework.http.ResponseEntity.

@RequestMapping(value="/stream", method=RequestMethod.GET)
public ResponseBodyEmitter handle() {
	   ResponseBodyEmitter emitter = new ResponseBodyEmitter();
	   // Pass the emitter to another component...
	   return emitter;
}

// in another thread
emitter.send(foo1);

// and again
emitter.send(foo2);

// and done
emitter.complete();
Authors
Rossen Stoyanchev, Juergen Hoeller
Since
4.2

Nested and Inner Type Summary

Modifier and TypeClass and Description
public static class
ResponseBodyEmitter.DataWithMediaType

A simple holder of data to be written along with a MediaType hint for selecting a message converter to write with.

private class
private class
pack-priv static interface
ResponseBodyEmitter.Handler

Contract to handle the sending of event data, the completion of event sending, and the registration of callbacks to be invoked in case of timeout, error, and completion for any reason (including from the container side).

Field Summary

Modifier and TypeField and Description
private boolean
complete

Store successful completion before the handler is initialized.

private final ResponseBodyEmitter.DefaultCallback
private final Set<ResponseBodyEmitter.DataWithMediaType>
earlySendAttempts

Store send data before handler is initialized.

private final ResponseBodyEmitter.ErrorCallback
private Throwable
failure

Store an error before the handler is initialized.

private ResponseBodyEmitter.Handler
private boolean
ioErrorOnSend

After an I/O error, we don't call completeWithError directly but wait for the Servlet container to call us via AsyncListener#onError on a container thread at which point we call completeWithError.

private final Long
private final ResponseBodyEmitter.DefaultCallback

Constructor Summary

AccessConstructor and Description
public
ResponseBodyEmitter()

Create a new ResponseBodyEmitter instance.

public
ResponseBodyEmitter(Long
the timeout value in milliseconds
timeout
)

Create a ResponseBodyEmitter with a custom timeout value.

Method Summary

Modifier and TypeMethod and Description
public synchronized void
complete()

Complete request processing by performing a dispatch into the servlet container, where Spring MVC is invoked once more, and completes the request processing lifecycle.

public synchronized void
completeWithError(Throwable ex)

Complete request processing with an error.

protected void
extendResponse(ServerHttpResponse outputMessage)

Invoked after the response is updated with the status code and headers, if the ResponseBodyEmitter is wrapped in a ResponseEntity, but before the response is committed, i.e. before the response body has been written to.

public Long
getTimeout()

Return the configured timeout value, if any.

pack-priv synchronized void
pack-priv synchronized void
public synchronized void
onCompletion(Runnable callback)

Register code to invoke when the async request completes.

public synchronized void
onError(Consumer<Throwable> callback)

Register code to invoke for an error during async request processing.

public synchronized void
onTimeout(Runnable callback)

Register code to invoke when the async request times out.

public void
send(Object
the object to write
object
)

Write the given object to the response.

public synchronized void
send(Object
the object to write
object
,
MediaType
a MediaType hint for selecting an HttpMessageConverter
mediaType
)

Overloaded variant of send(Object) that also accepts a MediaType hint for how to serialize the given Object.

public synchronized void
send(Set<ResponseBodyEmitter.DataWithMediaType>
the object and media type pairs to write
items
)

Write a set of data and MediaType pairs in a batch.

private void
public String
toString()

Overrides java.lang.Object.toString.

Returns a string representation of the object.

Inherited from java.lang.Object:
cloneequalsfinalizegetClasshashCodenotifynotifyAllwaitwaitwait

Field Detail

completeback to summary
private boolean complete

Store successful completion before the handler is initialized.

completionCallbackback to summary
private final ResponseBodyEmitter.DefaultCallback completionCallback
earlySendAttemptsback to summary
private final Set<ResponseBodyEmitter.DataWithMediaType> earlySendAttempts

Store send data before handler is initialized.

errorCallbackback to summary
private final ResponseBodyEmitter.ErrorCallback errorCallback
failureback to summary
private Throwable failure

Store an error before the handler is initialized.

Annotations
@Nullable
handlerback to summary
private ResponseBodyEmitter.Handler handler
Annotations
@Nullable
ioErrorOnSendback to summary
private boolean ioErrorOnSend

After an I/O error, we don't call completeWithError directly but wait for the Servlet container to call us via AsyncListener#onError on a container thread at which point we call completeWithError. This flag is used to ignore further calls to complete or completeWithError that may come for example from an application try-catch block on the thread of the I/O error.

timeoutback to summary
private final Long timeout
Annotations
@Nullable
timeoutCallbackback to summary
private final ResponseBodyEmitter.DefaultCallback timeoutCallback

Constructor Detail

ResponseBodyEmitterback to summary
public ResponseBodyEmitter()

Create a new ResponseBodyEmitter instance.

ResponseBodyEmitterback to summary
public ResponseBodyEmitter(Long timeout)

Create a ResponseBodyEmitter with a custom timeout value.

By default not set in which case the default configured in the MVC Java Config or the MVC namespace is used, or if that's not set, then the timeout depends on the default of the underlying server.

Parameters
timeout:Long

the timeout value in milliseconds

Method Detail

completeback to summary
public synchronized void complete()

Complete request processing by performing a dispatch into the servlet container, where Spring MVC is invoked once more, and completes the request processing lifecycle.

Note

this method should be called by the application to complete request processing. It should not be used after container related events such as an error while sending.

completeWithErrorback to summary
public synchronized void completeWithError(Throwable ex)

Complete request processing with an error.

A dispatch is made into the app server where Spring MVC will pass the exception through its exception handling mechanism. Note however that at this stage of request processing, the response is committed and the response status can no longer be changed.

Note

this method should be called by the application to complete request processing with an error. It should not be used after container related events such as an error while sending.

extendResponseback to summary
protected void extendResponse(ServerHttpResponse outputMessage)

Invoked after the response is updated with the status code and headers, if the ResponseBodyEmitter is wrapped in a ResponseEntity, but before the response is committed, i.e. before the response body has been written to.

The default implementation is empty.

getTimeoutback to summary
public Long getTimeout()

Return the configured timeout value, if any.

Annotations
@Nullable
initializeback to summary
pack-priv synchronized void initialize(ResponseBodyEmitter.Handler handler) throws IOException
initializeWithErrorback to summary
pack-priv synchronized void initializeWithError(Throwable ex)
onCompletionback to summary
public synchronized void onCompletion(Runnable callback)

Register code to invoke when the async request completes. This method is called from a container thread when an async request completed for any reason including timeout and network error. This method is useful for detecting that a ResponseBodyEmitter instance is no longer usable.

onErrorback to summary
public synchronized void onError(Consumer<Throwable> callback)

Register code to invoke for an error during async request processing. This method is called from a container thread when an error occurred while processing an async request.

Since
5.0
onTimeoutback to summary
public synchronized void onTimeout(Runnable callback)

Register code to invoke when the async request times out. This method is called from a container thread when an async request times out.

sendback to summary
public void send(Object object) throws IOException

Write the given object to the response.

If any exception occurs a dispatch is made back to the app server where Spring MVC will pass the exception through its exception handling mechanism.

Note

if the send fails with an IOException, you do not need to call completeWithError(Throwable) in order to clean up. Instead the Servlet container creates a notification that results in a dispatch where Spring MVC invokes exception resolvers and completes processing.

Parameters
object:Object

the object to write

Exceptions
IOException:
raised when an I/O error occurs
IllegalStateException:
wraps any other errors
sendback to summary
public synchronized void send(Object object, MediaType mediaType) throws IOException

Overloaded variant of send(Object) that also accepts a MediaType hint for how to serialize the given Object.

Parameters
object:Object

the object to write

mediaType:MediaType

a MediaType hint for selecting an HttpMessageConverter

Exceptions
IOException:
raised when an I/O error occurs
IllegalStateException:
wraps any other errors
sendback to summary
public synchronized void send(Set<ResponseBodyEmitter.DataWithMediaType> items) throws IOException

Write a set of data and MediaType pairs in a batch.

Compared to send(Object, MediaType), this batches the write operations and flushes to the network at the end.

Parameters
items:Set<ResponseBodyEmitter.DataWithMediaType>

the object and media type pairs to write

Exceptions
IOException:
raised when an I/O error occurs
IllegalStateException:
wraps any other errors
Since
6.0.12
sendInternalback to summary
private void sendInternal(Set<ResponseBodyEmitter.DataWithMediaType> items) throws IOException
toStringback to summary
public String toString()

Overrides java.lang.Object.toString.

Doc from java.lang.Object.toString.

Returns a string representation of the object. Satisfying this method's contract implies a non-null result must be returned.

Returns:String

a string representation of the object

Annotations
@Override
org.springframework.web.servlet.mvc.method.annotation back to summary

public Class ResponseBodyEmitter.DataWithMediaType

extends Object
Class Inheritance
  • java.lang.Object
  • org.springframework.web.servlet.mvc.method.annotation.ResponseBodyEmitter.DataWithMediaType

A simple holder of data to be written along with a MediaType hint for selecting a message converter to write with.

Field Summary

Modifier and TypeField and Description
private final Object
private final MediaType

Constructor Summary

AccessConstructor and Description
public

Method Summary

Modifier and TypeMethod and Description
public Object
public MediaType
Inherited from java.lang.Object:
cloneequalsfinalizegetClasshashCodenotifynotifyAlltoStringwaitwaitwait

Field Detail

databack to summary
private final Object data
mediaTypeback to summary
private final MediaType mediaType
Annotations
@Nullable

Constructor Detail

DataWithMediaTypeback to summary
public DataWithMediaType(Object data, MediaType mediaType)

Method Detail

getDataback to summary
public Object getData()
getMediaTypeback to summary
public MediaType getMediaType()
Annotations
@Nullable
org.springframework.web.servlet.mvc.method.annotation back to summary

private Class ResponseBodyEmitter.DefaultCallback

extends Object
implements Runnable
Class Inheritance
  • java.lang.Object
  • org.springframework.web.servlet.mvc.method.annotation.ResponseBodyEmitter.DefaultCallback
All Implemented Interfaces
java.lang.Runnable

Field Summary

Modifier and TypeField and Description
private Runnable

Constructor Summary

AccessConstructor and Description
private

Method Summary

Modifier and TypeMethod and Description
public void
run()

Implements java.lang.Runnable.run.

Runs this operation.

public void
Inherited from java.lang.Object:
cloneequalsfinalizegetClasshashCodenotifynotifyAlltoStringwaitwaitwait

Field Detail

delegateback to summary
private Runnable delegate
Annotations
@Nullable

Constructor Detail

DefaultCallbackback to summary
private DefaultCallback()

Method Detail

runback to summary
public void run()

Implements java.lang.Runnable.run.

Doc from java.lang.Runnable.run.

Runs this operation.

Annotations
@Override
setDelegateback to summary
public void setDelegate(Runnable delegate)
org.springframework.web.servlet.mvc.method.annotation back to summary

private Class ResponseBodyEmitter.ErrorCallback

extends Object
implements Consumer<Throwable>
Class Inheritance
  • java.lang.Object
  • org.springframework.web.servlet.mvc.method.annotation.ResponseBodyEmitter.ErrorCallback
All Implemented Interfaces
java.util.function.Consumer

Field Summary

Modifier and TypeField and Description
private Consumer<Throwable>

Constructor Summary

AccessConstructor and Description
private

Method Summary

Modifier and TypeMethod and Description
public void
accept(Throwable
the input argument
t
)

Implements java.util.function.Consumer.accept.

Performs this operation on the given argument.

public void
Inherited from java.lang.Object:
cloneequalsfinalizegetClasshashCodenotifynotifyAlltoStringwaitwaitwait

Field Detail

delegateback to summary
private Consumer<Throwable> delegate
Annotations
@Nullable

Constructor Detail

ErrorCallbackback to summary
private ErrorCallback()

Method Detail

acceptback to summary
public void accept(Throwable t)

Implements java.util.function.Consumer.accept.

Doc from java.util.function.Consumer.accept.

Performs this operation on the given argument.

Parameters
t:Throwable

the input argument

Annotations
@Override
setDelegateback to summary
public void setDelegate(Consumer<Throwable> callback)
org.springframework.web.servlet.mvc.method.annotation back to summary

pack-priv Interface ResponseBodyEmitter.Handler

Known Direct Implementers
org.springframework.web.servlet.mvc.method.annotation.ResponseBodyEmitterReturnValueHandler.HttpMessageConvertingHandler

Contract to handle the sending of event data, the completion of event sending, and the registration of callbacks to be invoked in case of timeout, error, and completion for any reason (including from the container side).

Method Summary

Modifier and TypeMethod and Description
public void
public void
public void
public void
public void
onTimeout(Runnable callback)

public void
send(Object data, MediaType mediaType)

Immediately write and flush the given data to the network.

public void
send(Set<ResponseBodyEmitter.DataWithMediaType> items)

Immediately write all data items then flush to the network.

Method Detail

completeback to summary
public void complete()
completeWithErrorback to summary
public void completeWithError(Throwable failure)
onCompletionback to summary
public void onCompletion(Runnable callback)
onErrorback to summary
public void onError(Consumer<Throwable> callback)
onTimeoutback to summary
public void onTimeout(Runnable callback)
sendback to summary
public void send(Object data, MediaType mediaType) throws IOException

Immediately write and flush the given data to the network.

sendback to summary
public void send(Set<ResponseBodyEmitter.DataWithMediaType> items) throws IOException

Immediately write all data items then flush to the network.

Since
6.0.12