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,ResponseEntity
additionally 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@ModelAttribute
parameters or explicit model by declaringModel
method parameter
View
β allows to return instance of view, likeJstlView
,ThymeleafView
,FreeMarkerView
, usually used with implicit model through@ModelAttribute
parameters or explicit model by declaringModel
method 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 usingServletResponse
orOutputStream
as parameter, or@ResponseStatus
annotation, if none of previous are usedRequestToViewNameTranslator
will identify view based on request,void
return type can also indicate βno response bodyβ for REST controllers
DeferredResult<V>
- allows to specify result for controller asynchronously from differentThread
or 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,SseEmitter
uses Server-Sent Events standardized with W3C SSE specification
StreamingResponseBody
β allows to write to the responseOutputStream
asynchronously
Reactive types
β allows to use Reactive types for streaming scenarios, handled byReactiveAdapterRegistry