You need to enable JavaScript to run this app. Spring Boot如何通过JSON请求体实现Person数据的更新与删除
优惠活动
大模型
产品
解决方案
定价
更多

Spring Boot如何通过JSON请求体实现Person数据的更新与删除

接口改造实现方案

改造核心是将原从路径变量、查询参数获取的参数,全部替换为从JSON请求体绑定获取,和你现有POST接口的传参逻辑保持一致,降低认知成本。

1. 改造后的Controller层代码

直接移除原接口里的@PathVariable、@RequestParam,用@RequestBody绑定请求里的JSON对象为Person实体,对应代码:

// PersonController类内的改造后方法
// 原@PostMapping、@GetMapping逻辑保持不变

// 改造后的删除接口 不再在路径中拼接personId
@DeleteMapping
public void deletePerson(@RequestBody Person person) {
    // 直接从请求体传入的Person对象中取需要删除的目标id
    personService.deletePerson(person.getId());
}

// 改造后的更新接口 不再在路径中拼接personId、不再用查询参数传值
@PutMapping
public void updatePerson(@RequestBody Person person) {
    // 直接把请求体传入的带id、更新字段的Person对象传给Service层
    personService.updatePerson(person);
}

2. 改造后的Service层代码

调整Service层方法的入参逻辑,适配Controller传过来的Person对象,同时兼容原有的数据校验逻辑,避免初学者踩坑:

@Service
public class PersonService {
    private final PersonRepository personRepository;

    // 构造器注入Repository 保持原有依赖注入逻辑
    @Autowired
    public PersonService(PersonRepository personRepository) {
        this.personRepository = personRepository;
    }

    /**
     * 删除人员逻辑 保持原有入参形式 不需要额外修改
     */
    public void deletePerson(Long personId) {
        boolean exists = personRepository.existsById(personId);
        if (!exists) {
            throw new IllegalStateException("ID为" + personId + "的人员数据不存在");
        }
        personRepository.deleteById(personId);
    }

    /**
     * 改造后的更新逻辑 直接接收请求体传入的Person对象
     */
    public void updatePerson(Person updatePerson) {
        Long targetId = updatePerson.getId();
        // 先查询目标数据是否存在
        Person existingPerson = personRepository.findById(targetId)
                .orElseThrow(() -> new IllegalStateException("ID为" + targetId + "的人员数据不存在"));
        
        // 仅覆盖请求体中非空的字段 避免未传的字段被误清空为null
        String newName = updatePerson.getName();
        if (newName != null && !newName.isBlank()) {
            existingPerson.setName(newName);
        }
        String newLastname = updatePerson.getLastname();
        if (newLastname != null && !newLastname.isBlank()) {
            existingPerson.setLastname(newLastname);
        }
        // 持久化更新后的对象
        personRepository.save(existingPerson);
    }
}

3. Postman测试注意事项

  • 所有使用@RequestBody的接口,请求Body需选择raw格式、JSON类型,不能再用URL拼接查询参数传值
  • 删除操作测试:请求方法选DELETE,地址为http://localhost:8080/api/v1/person,请求体传入{"id": 1}即可
  • 更新操作测试:请求方法选PUT,地址为http://localhost:8080/api/v1/person,请求体传入{"id": 1, "name": "更新后的名字", "lastname": "更新后的姓氏"}即可

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.26 12:36:03