Springboot @Controller | @RestController | @ResponseBody | @ResponseEntity | rest api | okay java

Опубликовано: 21 October 2024
на канале: okay java
9,610
242

Springboot @Controller | @RestController | @ResponseBody | @ResponseEntity | rest api | okay java
Buy me a coffee - https://www.buymeacoffee.com/okayjava
what is the difference between a REST API and a web application. ??
Response from a web application is generally view (HTML + CSS) because they are intended for human viewers.
REST API just returns data in form of JSON or XML because most of the REST clients are programs.

@Controller annotation
Used to mark a class as Spring MVC Controller.
To handle web request
Returns “view” (html response with model values)
Spring 2.5

@RestController annotation
@Controller + @ResponseBody.
To handle rest api request
Returns JSON/XML response
Spring 4.0

@ResponseBody annotation
Converts object into json format
To put this in simple words, @ResponseBody tell Spring framework to serialize a return object into JSON or XML and send this information back as part of the HTTPResponse.

Summary
@Controller create a Map of Model Object and find a view while @RestController simply return object and object data directly written into http response as JSON orXML.

The @RestController annotation in Spring MVC/Spring BOOT is nothing but a combination of @Controller and @ResponseBody annotation.

The key difference is that you do not need to use @ResponseBody on each and every handler method once you annotate the class with @RestController.