You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java编写返回201 HTTP状态码的POST接口实现问题咨询

调整方案

你可以根据是否需要返回响应内容/自定义响应头,选择以下两种实现方式:

方式1:最简实现(仅需返回201状态码,无额外响应内容)

直接在接口方法上添加@ResponseStatus注解指定状态码即可,调整后代码如下:

@PostMapping
@ResponseStatus(HttpStatus.CREATED)
public void registerCustomer(@RequestBody Customer customer){
    customerService.addCustomer(customer);
}

注意需要引入org.springframework.http.HttpStatus类。

方式2:标准REST规范实现(带Location响应头,可选返回资源内容)

HTTP 201状态码的规范要求通常需要返回Location响应头,指向新创建资源的访问地址,这种场景可以使用ResponseEntity构造响应,调整后代码如下:

@PostMapping
public ResponseEntity<Void> registerCustomer(@RequestBody Customer customer){
    // 新增客户后获取生成的客户ID
    Long customerId = customerService.addCustomer(customer);
    // 构造新资源的访问路径
    URI location = ServletUriComponentsBuilder.fromCurrentRequest()
                    .path("/{id}")
                    .buildAndExpand(customerId)
                    .toUri();
    // 返回201状态码+Location头
    return ResponseEntity.created(location).build();
}

如果需要将新建的客户信息返回给前端,可以把返回值泛型改成ResponseEntity<Customer>:

@PostMapping
public ResponseEntity<Customer> registerCustomer(@RequestBody Customer customer){
    Customer savedCustomer = customerService.addCustomer(customer);
    URI location = ServletUriComponentsBuilder.fromCurrentRequest()
                    .path("/{id}")
                    .buildAndExpand(savedCustomer.getId())
                    .toUri();
    return ResponseEntity.created(location).body(savedCustomer);
}

内容的提问来源于stack exchange,提问作者LearnJavaSpring

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 02:57:03