什么是@RestController注解?


使用idea進行,查看源碼解釋如下:

A convenience annotation that is itself annotated with @Controller and @ResponseBody.

Types that carry this annotation are treated as controllers where @RequestMapping methods assume @ResponseBody semantics by default.

翻譯過來的意思是:

一個便利性注解,其本身用@Controller和@ResponseBody進行注解。(其實,實現了二者注解功能的結合)

帶有此注釋的類型被視為控制器,其中@RequestMapping方法默認情況下采用@ResponseBody語義。

 

@ResponseBody注解:

作用: 

      該注解用於將Controller的方法返回的對象,通過適當的HttpMessageConverter轉換為指定格式后,寫入到Response對象的body數據區。

@RequestBody注解:

作用: 

      i) 該注解用於讀取Request請求的body部分數據,使用系統默認配置的HttpMessageConverter進行解析,然后把相應的數據綁定到要返回的對象上;

 

      ii) 再把HttpMessageConverter返回的對象數據綁定到 controller中方法的參數上。

A) GET、POST方式提時, 根據request header Content-Type的值來判斷:

  •     application/x-www-form-urlencoded, 可選(即非必須,因為這種情況的數據@RequestParam, @ModelAttribute也可以處理,當然@RequestBody也能處理);
  •     multipart/form-data, 不能處理(即使用@RequestBody不能處理這種格式的數據);
  •     其他格式, 必須(其他格式包括application/json, application/xml等。這些格式的數據,必須使用@RequestBody來處理);

B) PUT方式提交時, 根據request header Content-Type的值來判斷:

  •     application/x-www-form-urlencoded, 必須;
  •     multipart/form-data, 不能處理;
  •     其他格式, 必須;

說明:request的body部分的數據編碼格式由header部分的Content-Type指定;


 

使用@RestController注解:

1) 如果只是使用@RestController注解Controller,則Controller中的方法無法返回jsp頁面,或者html,配置的視圖解析器 InternalResourceViewResolver不起作用,返回的內容就是return 里的內容。

2) 如果需要返回到指定頁面,則需要用 @Controller配合視圖解析器InternalResourceViewResolver才行。
   

3) 如果需要返回JSON,XML或自定義mediaType內容到頁面,則需要在對應的方法上加上@ResponseBody注解。

參考鏈接:

https://blog.csdn.net/kobejayandy/article/details/12690555

https://blog.csdn.net/ZZ2713634772/article/details/79471710

 

 

 

 

 

A convenience annotation that is itself annotated with @Controller and @ResponseBody.

Types that carry this annotation are treated as controllers where @RequestMapping methods assume @ResponseBody semantics by default.


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM