前言:
本系列博客記錄 springboot 求學之路:
springboot 有很多請求方式,這裏記錄一下如題的一個疑問,
1.問題的由來
學習就要看書,書上有個例子,如下:
@Controller
public class TestController {
@GetMapping("/get")
public @ResponseBody Object getName() {
return "hello";
}
}
而網上的教程是這樣的:
@RestController
public class TestController {
@GetMapping("/get")
public Object getName() {
return "hello";
}
}
這兩個例子都沒問題,但是寫法風格不一樣,所以有必要探究一下
2.區別
@RestController加在類上面的註解,使得類裏面的每個方法都將 json/xml 返回數據加返回到前臺頁面中
@Controller加在類上面的註解,使得類裏面的每個方法都返回一個視圖頁面;
仔細看“視圖頁面”,1 中給的例子返回的可是字符串,很明顯不符合,爲了可以返回字符串,所以在類方法裏面多了一個@ResponseBody註解,它讓方法可以以 json/xml 形式返回。
3.總結
@RestController 返回json/xml
@Controller 返回視圖
如果需求是返回 json/xml 則 @RestController = @Controller + @ResponseBody
其中 @ResponseBody註解可以放到類上(類中方法都生效),也可以放在方法上,如下
@Controller
public class TestController {
@GetMapping("/get")
@ResponseBody
public Object getName() {
return "hello";
}
}