简介
在 Spring 中,ResponseEntity 是 HTTP 响应的包装器。它允许自定义响应的各个方面:
-
HTTP 状态码
-
响应主体
-
HTTP 请求头
使用 ResponseEntity 允许完全控制 HTTP 响应,并且它通常用于 RESTful Web 服务中从控制器方法返回响应。
基本语法
ResponseEntity<T> response = new ResponseEntity<>(body, headers, status);
-
T:响应主体的类型 -
body:想要作为响应主体发送的对象(如果不想返回主体,则可以为空) -
headers:想要包含的任何其他HTTP请求头 -
status:HTTP 状态代码(如HttpStatus.OK、HttpStatus.CREATED等)
示例用法
基本用法:返回简单响应
@RestController
@RequestMapping("/api/posts")
public class PostController {
@GetMapping("/{id}")
public ResponseEntity<Post> getPost(@PathVariable Long id) {
Post post = postService.findById(id);
if (post != null) {
return new ResponseEntity<>(post, HttpStatus.OK); // 200 OK
} else {
return new ResponseEntity<>(HttpStatus.NOT_FOUND); // 404 Not Found
}
}
}
返回带有请求头的 ResponseEntity
@GetMapping("/custom-header")
public ResponseEntity<String> getWithCustomHeader() {
HttpHeaders headers = new HttpHeaders();
headers.add("Custom-Header", "CustomValue");
return new ResponseEntity<>("Hello with custom header!", headers, HttpStatus.OK);
}
返回具有创建状态的 ResponseEntity
创建新资源时,通常希望返回
201 Created状态代码
@PostMapping("/create")
public ResponseEntity<Post> createPost(@RequestBody Post post) {
Post createdPost = postService.save(post);
URI location = ServletUriComponentsBuilder.fromCurrentRequest()
.path("/{id}")
.buildAndExpand(createdPost.getId())
.toUri();
return ResponseEntity.created<

最低0.47元/天 解锁文章
7164

被折叠的 条评论
为什么被折叠?



