Understanding of @RestController annotation
The role of @RestController in Spring
Equivalent to @Controller + @ResponseBody.
So I want to understand @RestController annotation
You need to understand the @Controller and @ResponseBody annotations first
@Controller annotation
Adding the @Controller annotation on a class indicates that this class is a controller class.
The description of Controller annotation is omitted here.
@ResponseBody annotation
@ResponseBody means that the return value of the method is written directly into the Http response body in the specified format, rather than parsing it into a jump path.
The conversion of the format is implemented by the method in HttpMessageConverter, because it is an interface, so the conversion is completed by its implementation class.
If the method is required to return json format data instead of jumping to the page, you can directly mark @RestController on the class instead of marking @ResponseBody in each method, simplifying the development process.
The difference between @Controller and @RestController:
@Controller:
- In the corresponding method, the view parser can parse the return jsp,html page and jump to the corresponding page
- If you return json and other content to the page, you need to add @ResponseBody annotation
@RestController:
- Equivalent to the combination of two annotations @Controller+@ResponseBody
- Returning json data does not require the @ResponseBody annotation before the method
- However, using the @RestController annotation, you cannot return the jsp,html page, and the view parser cannot parse the jsp,html page.
Code Example
BuyerProductController
/** * Buyer's Products * Created by Li Bolin * 2020/10/17 20:11 */ package ; import ; import ; import ; @RestController @RequestMapping("/buyer/product") public class BuyerProductController { @GetMapping("/list") public void list(){ } }
Summarize
The above is personal experience. I hope you can give you a reference and I hope you can support me more.