@RestController和@Controller

@RestController作用:
  註解整合了@Controller和@ResponseBody。使用了這個註解的類會被看作一個controller。controller中使用@RequestMapping的方法有一個默認的@ResponseBody註解。@ResponseBody也可以加到類一級,通過繼承方法一級不需要添加。
@Responsebody 作用:
  該註解用於將Controller的方法返回的對象,通過適當的HttpMessageConverter轉換爲指定格式後,寫入到Response對象的body數據區。
使用時機:
  返回的數據不是html標籤的頁面,而是其他某種格式的數據時(如json、xml等)使用。


官方文檔:
@RestController is a stereotype annotation that combines @ResponseBody and @Controller.
意思是:
@RestController註解相當於@ResponseBody + @Controller合在一起的作用。

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

例如:本來應該到success.jsp頁面的,則其顯示success.


2)如果需要返回到指定頁面,則需要用 @Controller配合視圖解析器InternalResourceViewResolver才行。
3)如果需要返回JSON,XML或自定義mediaType內容到頁面,則需要在對應的方法上加上@ResponseBody註解。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章