
讓我們來看看具有以下端點的控制器:
1 2 3 4 5 6 7 8 9 | @RestController
@RequestMapping( "v1/hello" )
public class ExampleController {
@GetMapping
public ResponseEntity<String> get() {
return ResponseEntity.ok( "Hello World!" );
}
}
|
登入後複製
使用Spring的@RestController註解時,預設將回應放在回應的body中,無需使用 ResponseEntity 輸入方法返回,直接輸入回應類型即可,如範例下圖:
1 2 3 4 5 6 7 8 9 | @RestController
@RequestMapping( "v1/hello" )
public class ExampleController {
@GetMapping
public String get() {
return "Hello World!" ;
}
}
|
登入後複製
另外,預設情況下,如果成功,端點中使用的狀態碼是200(OK),也就是說,只有當你想使用其他狀態時才需要更改它,並且不需使用ResponseEntity,只需使用註解即可@ResponseStatus以上方法:
1 2 3 4 5 6 7 8 9 10 | @RestController
@RequestMapping( "v1/hello" )
public class ExampleController {
@GetMapping
@ResponseStatus(HttpStatus.ACCEPTED)
public String get() {
return "Hello World!" ;
}
}
|
登入後複製
那為什麼ResponseEntity存在?
對於需要向回應添加更多資訊而不僅僅是正文和狀態的情況,例如向回應添加標頭:
1 2 3 4 5 6 7 8 9 10 11 | @RestController
@RequestMapping( "v1/hello" )
public class ExampleController {
@GetMapping
public ResponseEntity<String> get() {
return ResponseEntity.ok()
.header( "X-Test" , "Blabla" )
.body( "Hello World!" );
}
}
|
登入後複製
以上是何時使用 ResponseEntity?的詳細內容。更多資訊請關注PHP中文網其他相關文章!