開發RESTful API 時,通常都會在Controller上加上@Controller註解,可是有時候加上@RestController,當同事問爲何的時候,我也一臉懵逼,默默的看了資料,如今就說說他們的區別。html
@RestController註解等價於@ResponseBody + @Controller。@RestController和@Controller的共同點是都用來表示Spring某個類是否能夠接收HTTP請求,兩者區別: @RestController沒法返回指定頁面,而@Controller能夠;前者能夠直接返回數據,後者須要@ResponseBody輔助。下面詳細分析。java
① 是否能夠返回頁面web
答:@RestController沒法返回指定頁面,而@Controller能夠。
解析:對於Controller, 若是隻是使用@RestController註解,則其方法沒法返回指定頁面,此時配置的視圖解析器 InternalResourceViewResolver不起做用,返回的內容就是 return 裏的內容。 若是須要返回到指定頁面,則須要用 @Controller配合視圖解析器InternalResourceViewResolver才行。
② 返回內容
若是須要返回JSON,XML或自定義mediaType內容到頁面,@RestController本身就能夠搞定,這個註解對於返回數據比較方便,由於它會自動將對象實體轉換爲JSON格式。而@Controller須要在對應的方法加上@ResponseBody註解。spring
示例:json
import java.util.HashMap; import java.util.Map; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping("/difference") public class DifferenceController { // 跳轉到上傳文件的頁面 @RequestMapping(value = "/goToSuccessPage", method = RequestMethod.GET) public String goToSuccessPage() { // 跳轉到 視圖層 success.html return "success"; } @RequestMapping(value = "findAll", method = RequestMethod.GET) public Map<String, String> findAll() { Map<String, String> all = new HashMap<>(); all.put("remark", "能夠返回json,xml或自定義mediaType內容到頁面"); return all; } }