Spring 的 ResponseEntity 包装器使用详解

简介

Spring 中,ResponseEntityHTTP 响应的包装器。它允许自定义响应的各个方面:

  • 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<
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值