Spring MVC and Web Layer
August 23, 2021
M05 Q11 What are some of the valid return types of a controller method?
@ResponseBody– binds method return value to web response body, complex types will be converted with usage of HttpMessageConverter
HttpEntity,ResponseEntity- allows to specify full response with headers and body,ResponseEntityadditionally allows you to specify HTTP status code
HttpHeaders– allows to return response only with headers, without body
String– allows to return logical name of view to use when rendering response, view will be resolved byViewResolver, usually used with implicit model through@ModelAttributeparameters or explicit model by declaringModelmethod parameter
View– allows to return instance of view, likeJstlView,ThymeleafView,FreeMarkerView, usually used with implicit model through@ModelAttributeparameters or explicit model by declaringModelmethod parameter
Map,Model– allows you to specify attributes to be added to the implicit model, with the view name implicitly determined through aRequestToViewNameTranslator
@ModelAttribute– allows you to specify an attribute to be added to the model, with the view name implicitly determined through aRequestToViewNameTranslator
ModelAndView- view and model attributes to use and, optionally, a response status, view can be specified by logical name or instance of view can be passed, model can be specified as named object orMap
void– method that returns void can correctly handle request by usingServletResponseorOutputStreamas parameter, or@ResponseStatusannotation, if none of previous are usedRequestToViewNameTranslatorwill identify view based on request,voidreturn type can also indicate “no response body” for REST controllers
DeferredResult<V>- allows to specify result for controller asynchronously from differentThreador as result of some event callback, part of integration with Servlet 3.0 asynchronous request
Callable<V>- allows to produce return value asynchronously in a Spring MVC managed thread
ListenableFuture<V>,CompletableFuture<V>,CompletionStage<V >- allows to return set of chained, asynchronous operations, with callbacks and transformations
ResponseBodyEmitter,SseEmitter– allows to send objects in stream asynchronously, objects will be converted with usage ofHttpMessageConverter, can be used withResponseEntity, both classes have the same goal, however,SseEmitteruses Server-Sent Events standardized with W3C SSE specification
StreamingResponseBody– allows to write to the responseOutputStreamasynchronously
Reactive types– allows to use Reactive types for streaming scenarios, handled byReactiveAdapterRegistry