轉載
來源:部落格園
作者:大象踢足球
原文:https://www.cnblogs.com/Jason-Xiang/p/10244075.html
在傳統的開發過程中,我們的控制CONTROLLER層通常需要轉向一個JSP視圖;但随着WEB2.0相關技術的崛起,我們很多時候隻需要傳回資料即可,而不是一個JSP頁面。
- ResponseEntity:表示整個HTTP響應:狀态代碼,标題和正文。是以,我們可以使用它來完全配置HTTP響應,它是一個對象。
- @ResponseBody:傳回json格式的結果
- @ResponseStatus:傳回狀态
ResponseEntity
ResponseEntity是一種泛型類型。是以,我們可以使用任何類型作為響應主體:
@Controller
public class XXXController{
@GetMapping("/hello")
public ResponseEntity<String> hello() {
return new ResponseEntity<>("Hello World!", HttpStatus.OK);
}
這裡字元串"Hello World!"作為字元串傳回給REST端。
我們可以設定HTTP标頭:
@GetMapping("/customHeader")
ResponseEntity<String> customHeader() {
HttpHeaders headers = new HttpHeaders();
headers.add("Custom-Header", "foo");
return new ResponseEntity<>(
"Custom header set", headers, HttpStatus.OK);
}
設定自定義标頭:
@GetMapping("/customHeader")
ResponseEntity<String> customHeader() {
return ResponseEntity.ok()
.header("Custom-Header", "foo")
.body("Custom header set")
如果将一個對象放入:
@GetMapping("/hello")
public ResponseEntity<String> hello() {
return new ResponseEntity<>(new User(‘jdon’), HttpStatus.OK);
}
傳回的是JSON字元串:
[ { ‘name’: ‘jdon’}]
下面是傳回對象的JSON清單:
public ResponseEntity<List<ProcessDef>> repositoryProcessDefinitionsGet() {
return new ResponseEntity<>(processDefRepo.findAll(), HttpStatus.FOUND);
}
以上是通過ResponseEntity這個對象在代碼中靈活操控響應,但是在一般情況下我們隻是想傳回一個帶有資料的正常響應,那麼隻要使用@注解即可
@ResponseBody
在類級别使用@Controller标注情況下, @ResponseBody注解告訴傳回的對象将自動序列化為JSON,并通過回控制器的HttpResponse對象。
@Controller
public class XXXController{
@ResponseBody
public User postResponseController(@RequestBody LoginForm loginForm) {
return new User("Thanks For Posting!!!");
}
将傳回用戶端JSON字元串:
[ { ‘name’: Thanks For Posting!!!"}]
在@RestController注解了類的情況下,我們就不需要再使用@ResponseBody了。
@ResponseStatus
ResponseStatus雖然隻是規定了傳回的狀态,但是隻需要标注在方法上,簡單,而且狀态碼與傳回類型分離,比較清晰。我們将上面傳回對象清單的代碼使用ResponseStatus改寫如下,注意類級别@RestController:
@RestController
public class XXXController{
@ResponseStatus(HttpStatus.FOUND)
public User postResponseController() {
return new User("Thanks For Posting!!!");
}
這也會傳回用戶端JSON字元串:
[ { ‘name’: Thanks For Posting!!!"}]
這樣的代碼更加專注于業務。
直接操控響應
Spring還允許我們直接通路javax.servlet.http.HttpServletResponse對象; 我們隻需要将它聲明為方法參數:
@GetMapping("/manual")
public void manual(HttpServletResponse response) throws IOException {
response.setHeader("Custom-Header", "foo");
response.setStatus(200);
response.getWriter().println("Hello World!");
}
由于Spring在底層實作之上提供了抽象和附加功能,是以如果以這種方式直接操縱響應,會失去很多Spring提供友善功能。
參考:
SPRING MVC3.2案例講解–SPRING MVC3的@ResponseBody和ResponseEntity