@Controller and @RestController
@Controller
1. Returning Views with Controller
Traditional Spring MVC controller
Mainly used to return Views
Returns a ViewName!
A
ViewResolveris used to render a View from the ViewName returned by the ControllerFinds and renders a View according to the ViewResolver configuration
2. Returning Data with Controller
When data needs to be returned instead of a View, the
@ResponseBodyannotation must be used for data returnThe
@ResponseBodyannotation allows a Controller to return data in JSON format!The returned object is serialized to JSON and returned to the user
When returning objects through a Controller, they are generally wrapped in
ResponseEntityTo return objects,
HttpMessageConverteroperates instead ofViewResolverHttpMessageConverterhas several Converters registered, and the Converter used varies depending on the data to be returnedFor strings:
StringHttpMessageConverterFor objects:
MappingJackson2HttpMessageConverter
Spring combines the client's
Http Accept headerand the server's Controller return type information to select the appropriateHttpMessageConverterto process it
@RestController
Restful web service controller
@Controllerwith@ResponseBodyaddedAn HTTP Response Body is generated
The behavior is exactly the same as attaching
@ResponseBodyto@Controller!Allows using
@ResponseBody, which was previously declared on each method, all at once
The main purpose is to return object data in
JSON format!Mainly used when developing REST APIs, and objects are wrapped in
ResponseEntityfor return
Last updated